怎样正确 移除迭代器所指元素
来源:互联网 发布:淘宝卖奶粉需要什么 编辑:程序博客网 时间:2024/05/06 05:20
以下三段代码摘自《C++ 标准程序库》p204-205
代码段一:
- typedef std::map<std::string, float> StringFloatMap;
- StringFloatMap coll;
- StringFloatMap::iterator pos;
- //...
- for (pos = coll.begin(); pos != coll.end(); ++pos)
- {
- if (pos->second == value)
- {
- coll.erase(pos); // RUNTIME ERROR !!!
- }
- }
代码段 二:
- // 如果 erase() 总是返回下一元素的位置, 那就好办了,如下
- typedef std::map<std::string, float> StringFloatMap;
- StringFloatMap coll;
- StringFloatMap::iterator pos;
- //...
- for (pos = coll.begin(); pos != coll.end(); )
- {
- if (pos->second == value)
- {
- pos = coll.erase(pos); // would be fine, but COMPLILE TIME ERROR!!!
- }
- else
- {
- ++ pos;
- }
- }
代码段三: 完整且正确的哦
- #include <vector>
- #include <string>
- #include <iostream>
- #include <map>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- typedef map<string, int> StringIntMap;
- StringIntMap coll;
- coll.insert(make_pair("one", 1));
- coll.insert(make_pair("two", 2));
- coll.insert(make_pair("three", 3));
- coll.insert(make_pair("four", 4));
- {
- cout << "称除元素前: " << endl;
- StringIntMap::iterator itBeg = coll.begin();
- StringIntMap::iterator itEnd = coll.end();
- for (NULL; itBeg != itEnd; ++itBeg)
- {
- cout << itBeg->first << "---> " << itBeg->second << endl;
- }
- }
- { // 重点看这一段 ************************************************************
- // 移除值为"2" 的项
- StringIntMap::iterator itBeg = coll.begin();
- StringIntMap::iterator itEnd = coll.end();
- for (NULL; itBeg != itEnd; )
- {
- if (itBeg->second == 2)
- {
- coll.erase(itBeg ++ ); // 重点分析这一句:
- }
- else
- {
- ++itBeg;
- }
- }
- // 分析: 注意这一句相当于
- // 1.StringIntMap::iterator itTmp = itBeg;
- // 2. itBeg 自增.指向下一个元素
- // 3. coll.erase(itTmp); // 注意哦,调用erase后 迭代器无效, 但是这里是临时的对象,不怕....
- // 更详解决可看 标准库的源码,或者看类似的解释 http://blog.csdn.net/w_sx12553/article/details/8507188
- } // 重点看这一段 ************************************************************
- cout << endl << "称除元素后: " << endl;
- {
- StringIntMap::iterator itBeg = coll.begin();
- StringIntMap::iterator itEnd = coll.end();
- for (NULL; itBeg != itEnd; ++itBeg)
- {
- cout << itBeg->first << "---> " << itBeg->second << endl;
- }
- }
- return 0;
- }
0 0
- 怎样正确 移除迭代器所指元素
- 怎样正确 移除迭代器所指元素
- C++标准库---迭代器失效之正确的插入和移除元素
- iterator移除元素
- List移除元素
- 计蒜客 元素移除
- 移除DOM元素
- QVector移除元素
- 元素移除
- 移除元素
- 移除0元素
- 元素移除
- 计蒜客 -- 元素移除
- 计蒜客 元素移除
- 移除元素方法
- python 元素移除
- QVBoxLayout正确移除控件
- 标准库容器怎样移除与某一值相等的所有元素
- linux 路由表 的一些相关资料
- 菲绑匪索要7000万赎金,该不该给?
- 电视接口的AV,S端子,色差,VGA,DVI区别
- 是的感觉阿桑地方
- c++ static 关键字
- 怎样正确 移除迭代器所指元素
- Iori的工具箱 之 C# 实现多个图片合为一个Tiff
- iOS中百度地图API的总结
- javascript测试框架 Qunit
- 你从那个冬季走来
- 那一世、浮生若梦,这一季、倦卧红尘
- 中小企业的移动互联网“船票”
- 我相信越努力越幸运
- ios 学习博客及URL