有时候会有这么一种不太常见的需求:从一个map中删除所有符合某种条件的项目,而这种条件与map的key基本没啥关系。
比如,一个存储学生花名册的map,key为学号(int),value为姓名(string),如果要按学号删除很容易,但如果需要删除该map中所有姓“张”的学生,就只能遍历它,逐一比较了。
- using namespace std;
- typedef map<int, string> MAP;
- static bool canDrop(const MAP::value_type & v) {
- return 0 == strncmp(v.second.c_str(), "张", 2);
- }
下面是显而易见的错误方法 :
-
- for (MAP::iterator it = theMap.begin(); theMap.end()!=it; ++it) {
- if (canDrop(*it)) {
-
- theMap.erase(it);
- }
- }
如果用的是VC编译器,由于它对erase方法的扩展,所以用下面的方法,可以正确完成需求:
-
- for (MAP::iterator it = theMap.begin(); theMap.end()!=it;) {
- if (canDrop(*it)) {
-
- it = theMap.erase(it);
- } else {
- ++ it;
- }
- }
可惜,C++标准中的map::erase()方法并不返回任何值,所以上述代码在g++等编译器中无法通过编译。为了符合标准,下面有一种安全的方法——即将不需要删除的项Copy到另一个新的容器里,然后交换两个容器的内容。
-
- MAP tmp;
- for (MAP::iterator it = theMap.begin(); theMap.end()!=it; ++it) {
- if (!canDrop(*it)) {
-
- tmp.insert(*it);
- }
- }
- theMap.swap(tmp);
这种“复制不需要删除项到临时容器”的方法符合C++标准,也很容易理解,但如果不需要删除的项目数很多时(或者MAP的值拷贝开销很大时),就不太适合了。下面是另一种方法:
-
- for (MAP::iterator it = theMap.begin(); theMap.end()!=it;) {
- if (canDrop(*it)) {
-
-
- theMap.erase(it++);
- } else {
- ++it;
- }
- }
上例中,it++这个操作,首先保存了it的原始值,然后对it进行自增操作,由于此时erase尚未被调用,所以it的原始值有效,自增后的it也是有效的;然后,将it的原始值传递给erase()方法,正确地删掉项目。
现在的问题是,map的erase操作,除了影响被删除项目的iterator(使指向这个项目的iterator变成无效),还会影响其它iterator吗?比如说,下面这种方法来完成需求:
-
- vector<MAP::iterator> itList;
-
- for (MAP::iterator it=theMap.begin(); theMap.end() != it; ++it) {
- if (canDrop(*it)) {
- itList.push_back(it);
- }
- }
-
- for (vector<MAP::iterator>::iterator it2 = itList.begin(); itList.end() != it2; ++it2) {
- theMap.erase( *it2 );
- }
从测试结果来看,那些保存在临时容器里的iterator,并不因为其它iterator的失效而失效。