1. 定义
//C++98
(1) void erase (iterator position);
(2) size_type erase (const key_type& k);
(3) void erase (iterator first, iterator last);
//C++11
(1) iterator erase (const_iterator position);
(2) size_type erase (const key_type& k);
(3) iterator erase (const_iterator first, const_iterator last);
2. 参数
position:
Iterator pointing to a single element to be removed from the map.
This shall point to a valid and dereferenceable element.
Member types iterator and const_iterator are bidirectional
iterator types that point to elements.
k:
Key of the element to be removed from the map.
Member type key_type is the type of the elements in the container,
defined in map as an alias of its first template parameter (Key).
first, last:
Iterators specifying a range within the map container to be removed:
[first,last). i.e., the range includes all the elements between first and last,
including the element pointed by first but not the one pointed by last.
Member types iterator and const_iterator are bidirectional
iterator types that point to elements.
3. 返回值
(A)
For the key-based version (2), the function returns the number of elements erased,
which in map containers is at most 1.
Member type size_type is an unsigned integral type.
(B)
//对C++98
The other versions return no value.
//对C++11
The other versions return an iterator to the element that
follows the last element removed (or map::end, if the last element was removed).
Member type iterator is a bidirectional iterator type that points to an element.
4. 应用
例子1:
//删除单个节点
map<string,string> mapTest;
typedef map<string,string>::iterator ITER;
ITER iter=mapTest.find(key);
mapTest.erase(iter);
例子2:
//应用到循环里的错误写法。结果:导致程序的行为不可知。
//原因: map 是关联容器,对于关联容器来说,如果某一个元素已经被删除,
//那么其对应的迭代器就失效了,不应该再被使用;否则会导致程序无定义的行为。
for(ITER iter=mapTest.begin();iter!=mapTest.end();++iter)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter);
}
例子3:
//1.使用删除之前的迭代器定位下一个元素。STL建议的使用方式
for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter++);
}
//2. erase() 成员函数返回下一个元素的迭代器 (仅适用于C++11)
for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
cout<<iter->first<<":"<<iter->second<<endl;
iter=mapTest.erase(iter);
}
//3. 在删除iter指向的内容之前就将其移动到下一个正确地址,所以正确写法如下:
for( ITER iter = mapTest.begin(); iter != mapTest.end(); )
{
if( check(iter) )
{
mapTest.erase(iter++);
}
else
++iter;
}
或:
for( ITER iter = mapTest.begin(); iter != mapTest.end(); )
{
if( check(iter) )
{
mapTest.erase(iter++);
continue;
}
++iter;
}
//不止是map, 链式存储结构的stl容器都会这样,
//而对vector. string连续存储来说,就删除一个元素的时候不需要将迭代器++了.
参考文献:
[1]http://www.cplusplus.com/reference/map/map/erase/
[2]http://www.cnblogs.com/kex1n/archive/2011/12/06/2278505.html 博主:小 楼 一 夜 听 春 雨