[C++]How to use erase of std map correctly
keywords: [C++]How to use erase of std map correctly
Origin Text: http://www.cnblogs.com/graphics/archive/2010/07/05/1771110.html
#include <iostream>
#include <map>
#include <string>
using namespace std ;
int main(void)
{
map<int, string> m ;
m.insert(pair<int, string>(1, "abc")) ;
m.insert(pair<int, string>(2, "def")) ;
m.insert(pair<int, string>(3, "def")) ;
m.insert(pair<int, string>(4, "ghi")) ;
map<int, string>::iterator itor ;
// Print m
map<int, string>::const_iterator citor ;
for (citor = m.begin(); citor != m.end(); ++citor)
{
cout << citor->first << ":" << citor->second << endl ;
}
return 0 ;
}
Wrong way 1st:
for (itor = m.begin(); itor != m.end(); ++itor)
{
if (itor->second == "def")
{
//because map is associative container,iterator would be invalid when invoke erase
m.erase(itor);
}
}
Wrong way 2nd:
for (itor = m.begin(); itor != m.end(); ++itor)
{
if (itor->second != "def")
{
//++itor would be invoked twice, so it's possible to make iterator invalid.
m.erase(itor++);
}
}
Right way 1st:
for (itor = m.begin(); itor != m.end();)
{
if (itor->second == "def")
{
m.erase(itor++) ;
}
else
{
++itor;
}
}
Right way 2nd:
//erase would return a valid iterator when element deleted.
//notice that not all STL version would return value, erase of SGI STL would not return value, VC STL would be.
for (itor = m.begin(); itor != m.end();)
{
if (itor->second == "def")
{
//erase would return the next element of current deleted element.
itor = m.erase(itor);
}
else
{
++itor;
}
}
世上所有的惊喜和好运,等于你的人品乘以你的努力。