vector

Two kinds of overloading

Iterator erase(iterator _Where);

Iterator erase(iterator _First, iterator _Last); Erase () returns an iterator pointing to the element next to the deleted element; If a range of elements is deleted: the return value also represents an iterator, pointing to the element after the last element to be deleted;

Error:

{   for(Iter = v1.begin(); Iter != v1.end(); Iter++)
	if(*Iter == 10)
	{       
		v1.erase(Iter);
	} 
}
Copy the code

When we call erase() the Iter iterator is invalidated and becomes a wild pointer.

A seemingly correct correction:

for(Iter = v1.begin(); Iter ! = v1.end(); Iter++) { if(*Iter == 1) { Iter = v1.erase(Iter); // When erase, the old container is reorganized into a new container.Copy the code

There are two problems with this method :(1) the same value cannot be continuously deleted (1 in this case); (2) If the value is the last value to be deleted, Iter points to end(), and ++ is the error.

Solutions:

for(Iter = v1.begin(); Iter ! = v1.end(); ) { if(*Iter == 1) Iter = v1.erase(Iter); else Iter++; }Copy the code

map

There are three kinds of overloads in map

C++ 11 map erase returns a value

Iterator erase(iterator position);

Size_type erase(const key_type& x); If size_type is int, a value of 1 indicates that the deletion succeeded, and a value of 0 indicates that the deletion failed.

Iterator erase(iterator first, iterator last); // equivalent to map.clean().

The wrong condition has occurred

Map is an associative container and the iterator is invalidated when we call erase

std::map<int, int> mmap; mmap[0] = 0; mmap[1] = 1; mmap[2] = 2; mmap[3] = 3; std::map<int, int>:: iterator it = mmap.begin(); for( ; it! =mmap.end(); it++) { if(it->first == 2) { mmap.erase(it); // After execution, it fails and the program crashes. }}Copy the code

The right solution

The first kind of

for( ; it! =mmap.end(); ) { if(it->first == 2) { mmap.erase(it++); } else it++; }Copy the code

The second,

for( ; it! =mmap.end();) { if(it->first == 2) { it = mmap.erase(it); } else it++; }Copy the code