1. delete an element.
For example, if m IDs are saved in vector vecID, the nth IDs must be deleted.
Traversal is a method, that is, vector: itertor it = vecID. begin (); then ++ it n times.
A better method is: vector: itertor it = vecID. begin () + n; the vector iterator directly supports this offset.
Then, use vecID. erase (it) to delete the element.
2. Remove all objects with specific values in a container
1) if the container is a vector, string, or deque, use erase-remove. For example:
C. erase (remove (c. begin (), c. end (), 1963), c. end ());
2) If the container is list, use list. remove
// When c is a list, the remove member function is the best method to remove elements with specific values.
C. remove (1963 );
3) if the container is a standard associated container, use its erase member function, for example:
// When c is a standard associated container, the erase member function is the best method to remove elements with specific values.
C. erase (1963 );
3. Remove all objects in a container that meet a specific criterion
Bool badValue (int x); // Function Definition: returns whether x is "bad"
O if the container is a vector, string, or deque, use the erase-remove_if usage:
// When c is a vector, string, or deque, this is the best way to remove badValue and return a real object.
C. erase (remove_if (c. begin (), c. end (), badValue), c. end ());
O if the container is list, use list. remove_if:
// When c is list, this is the best way to remove badValue and return the real object.
C. remove_if (badValue );
O if the container is a standard associated container, use remove_copy_if and swap.
O if you need to write a circular traversal container element erase, pay attention to the incremental logic of iterator
// Error code: When an element of the container is deleted, all iterators pointing to that element become invalid.
AssocContainer <int> c;
// Do not do this!
For (AssocContainer <int>: iterator I = c. begin (); I! = C. end (); ++ I)
{
If (badValue (* I ))
{
C. erase (I );
}
}
// Correct code:
AssocContainer <int> c;
// The third part of the for Loop is empty, and I is auto-incrementing later.
For (AssocContainer <int>: iterator I = c. begin (); I! = C. end ();)
{
If (badValue (* I ))
{
I = c. erase (I); // only applicable to sequential containers. c. erase (I ++) is used for associated containers. void is returned for the associated container erase,
}
Else
{
++ I;
}
} (# Add wonderful)