返回信息流在看C++ Primer的时候,说是删除容器的元素会使指向已删除元素的迭代器失效,但是我下面的代码为什么还能用原来的iterator打印出删除掉的元素呢?
#include <iostream>
#include <set>
#include <exception>
using namespace std;
int main(int argc, char* argv[]) {
try {
set<int> s;
for (int i = 0; i < 15; i++) {
s.insert(s.end(), i);
}
set<int>::iterator pre = NULL;
set<int>::iterator post = NULL;
set<int>::iterator rand = NULL;
pre = s.find(10);
post = s.find(14);
rand = s.find(5);
s.erase(pre);
cout << "pre element: " << *pre << endl;
cout << "post element: " << *post << endl;
cout << "rand element: " << *rand << endl;
for (set<int>::iterator itr = s.begin(); itr != s.end(); itr++) {
cout << *itr << endl;
}
} catch (exception re) {
cout << " there is a exception !" << endl;
}
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #19264同步于 2009/2/16
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
【求助】C++的容器iterator失效的问题
satan200215
2009/2/16镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
【 在 satan200215 的大作中提到: 】
: 在看C++ Primer的时候,说是删除容器的元素会使指向已删除元素的迭代器失效,但是我下面的代码为什么还能用原来的iterator打印出删除掉的元素呢?
: #include <iostream>
: #include <set>
: ...................
怎么可能呢?
我在VC IDE下确认过了:
[color=#DC143C]s.erase(pre); 使得pre这个迭代器失效, 不信,用Watch看看
cout << "pre element: " << *pre << endl; 这一句, 肯定崩溃