迭代器在移除元素时迭代器可能失效。
vector如果开辟新的内存时迭代器可能失效。
新增元素时尾迭代器可能失效。
......
#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <map>
#include <set>
using namespace std;
int main()
{
{
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vector<int>::iterator ite = vec.begin();
cout << "vec:" << *ite << endl;
ite = vec.erase(ite);
//vec.erase(ite);
cout << "vec:" << *ite << endl;
}
cout << endl;
{
list<int> List;
List.push_back(1);
List.push_back(2);
list<int>::iterator ite = List.begin();
cout << "List:" << *ite << endl;
ite = List.erase(ite);
//List.erase(ite);
cout << "List:" << *ite << endl;
}
cout << endl;
{
deque<int> Deque;
Deque.push_back(1);
Deque.push_back(2);
deque<int>::iterator ite = Deque.begin();
cout << "Deque:" << *ite << endl;
ite = Deque.erase(ite);
//Deque.erase(ite);
cout << "Deque:" << *ite << endl;
}
cout << endl;
{
map<int, int> nnmap;
nnmap.insert(map<int, int>::value_type(1, 1));
nnmap.insert(map<int, int>::value_type(2, 2));
map<int, int>::iterator ite = nnmap.begin();
cout << "nnmap:" << ite->first << endl;
ite = nnmap.erase(ite);
//nnmap.erase(ite);
cout << "nnmap:" << ite->first << endl;
}
cout << endl;
{
set<int> Set;
Set.insert(1);
Set.insert(2);
set<int>::iterator ite = Set.begin();
cout << "Set:" << *ite << endl;
ite = Set.erase(ite);
//Set.erase(ite);
cout << "Set:" << *ite << endl;
}
return 0;
}
网友评论