iterater的erase

来源:互联网 发布:海洛因的网络名称 编辑:程序博客网 时间:2024/05/04 03:55

(http://blog.csdn.net/seawave/article/details/4401847)

有时候会有这么一种不太常见的需求:从一个map中删除所有符合某种条件的项目,而这种条件与map的key基本没啥关系。

比如,一个存储学生花名册的map,key为学号(int),value为姓名(string),如果要按学号删除很容易,但如果需要删除该map中所有姓“张”的学生,就只能遍历它,逐一比较了。

[cpp] view plaincopyprint?
  1. using namespace std;  
  2. typedef map<int, string> MAP;  
  3. static bool canDrop(const MAP::value_type & v) {  
  4.     return 0 == strncmp(v.second.c_str(), "张", 2);  
  5. }  

下面是显而易见的错误方法

[cpp] view plaincopyprint?
  1. // 第一种方法(错误的方法)!!   
  2. for (MAP::iterator it = theMap.begin(); theMap.end()!=it; ++it) {  
  3.     if (canDrop(*it)) {  
  4.         // 错误:当erase执行以后,it立刻就失效了,在执行到for循环的++it时就会出现未知后果。  
  5.         theMap.erase(it);  
  6.      }  
  7.  }  

如果用的是VC编译器,由于它对erase方法的扩展,所以用下面的方法,可以正确完成需求:

[cpp] view plaincopyprint?
  1. // 第2种方法,仅适用于VC   
  2. for (MAP::iterator it = theMap.begin(); theMap.end()!=it;) {  
  3.     if (canDrop(*it)) {  
  4.         // VC扩展了erase方法,使它返回下一个合法的迭代器   
  5.         it = theMap.erase(it);  
  6.     } else {  
  7.         ++ it;  
  8.     }  
  9. }   

可惜,C++标准中的map::erase()方法并不返回任何值,所以上述代码在g++等编译器中无法通过编译。为了符合标准,下面有一种安全的方法——即将不需要删除的项Copy到另一个新的容器里,然后交换两个容器的内容。

[cpp] view plaincopyprint?
  1. // 第3种方法,适用任何编译器,但有额外开销   
  2. MAP tmp; // 临时容器   
  3. for (MAP::iterator it = theMap.begin(); theMap.end()!=it; ++it) {  
  4.     if (!canDrop(*it)) {  
  5.         // 复制不需要删除的荐到临时容器   
  6.         tmp.insert(*it);  
  7.     }  
  8. }  
  9. theMap.swap(tmp); // 交换两个容器的内部,此时 theMap 中包含正确的项  

这种“复制不需要删除项到临时容器”的方法符合C++标准,也很容易理解,但如果不需要删除的项目数很多时(或者MAP的值拷贝开销很大时),就不太适合了。下面是另一种方法:

[cpp] view plaincopyprint?
  1. // 第4种方法   
  2. for (MAP::iterator it = theMap.begin(); theMap.end()!=it;) {  
  3.     if (canDrop(*it)) {  
  4.         // 在erase之前,先递增迭代器,此时由于erase尚未被调用,所以递增后的迭代器有效  
  5.         // 然后用迭代器的原始值来调用erase,确何删除正确的荐  
  6.         theMap.erase(it++);  
  7.     } else {  
  8.         ++it;  
  9.     }  
  10. }  

上例中,it++这个操作,首先保存了it的原始值,然后对it进行自增操作,由于此时erase尚未被调用,所以it的原始值有效,自增后的it也是有效的;然后,将it的原始值传递给erase()方法,正确地删掉项目。

现在的问题是,map的erase操作,除了影响被删除项目的iterator(使指向这个项目的iterator变成无效),还会影响其它iterator吗?比如说,下面这种方法来完成需求:

[cpp] view plaincopyprint?
  1. // 第5种方法   
  2. vector<MAP::iterator> itList;  
  3. // 保存所有要删除项目的iterator到临时容器   
  4. for (MAP::iterator it=theMap.begin(); theMap.end() != it; ++it) {  
  5.     if (canDrop(*it)) {  
  6.         itList.push_back(it);  
  7.     }  
  8. }  
  9. // 遍历临时容器,取出里面的iterator,逐一删除   
  10. for (vector<MAP::iterator>::iterator it2 = itList.begin(); itList.end() != it2; ++it2) {  
  11.     theMap.erase( *it2 );  
  12. }  

从测试结果来看,那些保存在临时容器里的iterator,并不因为其它iterator的失效而失效。

不过,这是C++标准吗?如果标准的确规定了erase并不影响其它iterator,那么第四种方法显然是最好的……可惜我查了半天没查到。有知道的达人不妨告诉我一声,谢谢。

0 0
原创粉丝点击