map基础

program2050 2014-05-27 10:13:11
用map::iterator指向了一个元素,然后其他地方操作了这个map,但是不动这个iterator,这个iterator的指向没有变。
难道map里面的红黑树左旋右旋的时候,不会影响这个iterator。没看过map的源码。呵呵。。。
是因为我的代码片面,具有偶然性,还是map的iterator的实现就是如此?

linux g++


#include <iostream>
#include <map>

using namespace std;

int main(int argc, char** argv)
{
map<int32_t, string> testMap;
testMap.insert(make_pair(1, "one"));
testMap.insert(make_pair(2, "two"));
map<int32_t, string>::iterator iter = testMap.begin();
for (; iter != testMap.end(); iter++) {
cout << "iter = (" << iter->first << " --> " << iter->second << ")." << endl;
}

map<int32_t, string>::iterator it = testMap.find(1);
cout << "it = (" << it->first << " --> " << it->second << ")." << endl;
map<int32_t, string>::iterator jt = testMap.find(2);
cout << "jt = (" << jt->first << " --> " << jt->second << ")." << endl;

/*testMap.erase(jt);
cout << "it = (" << it->first << " --> " << it->second << ")." << endl;*/
testMap.erase(it);
cout << "jt = (" << jt->first << " --> " << jt->second << ")." << endl;

testMap.insert(make_pair(3, "three"));
testMap.insert(make_pair(4, "four"));
testMap.insert(make_pair(5, "five"));
iter = testMap.begin();
for (; iter != testMap.end(); iter++) {
cout << "iter = (" << iter->first << " --> " << iter->second << ")." << endl;
}

it = testMap.find(4);
cout << "it = (" << it->first << " --> " << it->second << ")." << endl;

testMap.erase(it);
cout << "jt = (" << jt->first << " --> " << jt->second << ")." << endl;

return 0;

}
...全文
124 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ztenv 版主 2014-05-27
  • 打赏
  • 举报
回复
内部机制对你是透明的,如果影响了反而是设计的问题

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧