#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
using namespace std;
void stl_vector_test()
{
cout << "void stl_vector_test()" << endl;
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::iterator it = v.begin();
cout << "删除迭代器指向的元素,返回下一个元素的迭代器,原迭代器失效" << endl;
for (it = v.begin(); it != v.end(); ++it)
{
if (*it == 2)
{
#if 0
v.erase(it); //错误
#else
it = v.erase(it);
#endif
}
cout << *it;
}
cout << endl;
cout << "插在迭代器指向的元素前面,返回指向这个元素的迭代器,原迭代器失效" << endl;
for (it = v.begin(); it != v.end(); ++it)
{
if (*it == 3)
{
#if 0
v.insert(it, 4); //错误
#else
it = v.insert(it, 4);
#endif
break;
}
}
for (it = v.begin(); it != v.end(); ++it)
{
cout << *it;
}
cout << endl;
cout << "capacity变化之后,所有的迭代器都失效" << endl;
it = v.begin();
#if 0
for (int i = 0; i < 9999; ++i){ v.push_back(5); } //错误
#endif
while (it != v.end())
{
cout << *it++;
}
cout << endl;
cout << "容器对象交换元素后,迭代器也交换" << endl;
vector<int> other_v;
other_v.push_back(99);
other_v.push_back(88);
it = v.begin();
v.swap(other_v);
#if 0
for (; it != v.end(); ++it) //错误
#else
for (; it != other_v.end(); ++it)
#endif
{
cout << *it;
}
cout << endl;
}
void stl_list_test()
{
cout << "void stl_list_test()" << endl;
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
list<int>::iterator it = l.begin();
cout << "删除迭代器指向的元素,返回下一个元素的迭代器,原迭代器失效" << endl;
for (it = l.begin(); it != l.end(); ++it)
{
if (*it == 2)
{
#if 0
v.erase(it); //错误
#else
it = l.erase(it);
#endif
}
cout << *it;
}
cout << endl;
cout << "插在迭代器指向的元素前面,返回指向这个元素的迭代器,原迭代器失效" << endl;
for (it = l.begin(); it != l.end(); ++it)
{
if (*it == 3)
{
#if 0
v.insert(it, 4); //错误
#else
it = l.insert(it, 4);
#endif
break;
}
}
for (it = l.begin(); it != l.end(); ++it)
{
cout << *it;
}
cout << endl;
cout << "删除所有4的元素,他们的迭代器失效" << endl;
#if 0
l.remove(4);
#endif
cout << "容器对象交换元素后,迭代器也交换" << endl;
list<int> other_l;
other_l.push_back(99);
other_l.push_back(88);
it = l.begin();
l.swap(other_l);
#if 0
for (; it != v.end(); ++it) //错误
#else
for (; it != other_l.end(); ++it)
#endif
{
cout << *it;
}
cout << endl;
}
void stl_map_test()
{
cout << "void stl_map_test()" << endl;
map<int, string> m;
m[0] = "index_0";
m[1] = "index_1";
m[2] = "index_2";
map<int, string>::iterator it = m.begin();
cout << "删除迭代器指向的元素,返回下一个元素的迭代器,原迭代器失效" << endl;
while (it != m.end())
{
if(it->first == 1)
#if 0
m.erase(it);
#else
it = m.erase(it);
#endif
cout << it->first << " = " << it->second << endl;
it++;
}
}
int main()
{
/*序列容器*/
stl_vector_test();
stl_list_test();
/*关联容器*/
stl_map_test();
cout << endl;
system("pause");
return 0;
}
STL迭代器失效情况总结
最新推荐文章于 2024-04-01 21:31:23 发布