迭代器的基本用法
int main()
{
string str1 = "123456";
string::iterator it = str1.begin();//iterator为string中的一个类型,定义了it这个对象
while ( it != str1.end())
{
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
迭代器的作用
- 为了通用,因为C++中有很多的内数据类型,每一种数据类型的访问都有自己的方式,不容易记住,所以引入了迭代器
- 当进行增加或者删除额操作之后,一定要重新获取迭代器,因为增加或者删除的操作有可能造成迭代器失效
int main()
{
vector<int>v1;
for (int i = 1; i <= 10; i++)
{
v1.push_back(i);
}
vector<int>::iterator it = v1.begin();
while ( it != v1.end())
{
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
int main()
{
string str1 = "123456";
string::iterator it = str1.begin();
while (it != str1.end())
{
if (*it == '3')
{
str1.insert(it, 'i');//迭代器失效,程序崩溃,需要重新给迭代器赋值
}
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
int main()
{
string str1 = "123456";
string::iterator it = str1.begin();
while (it != str1.end())
{
if (*it == '3')
{
it = str1.insert(it, 'i');//给迭代器重新赋值后,迭代器没失效,但是造成了死循环
}
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
int main()
{
string str1 = "123456";
string::iterator it = str1.begin();
while (it != str1.end())
{
if (*it == '3')
{
it = str1.insert(it, 'i');//返回后迭代器指向了i所在的位置
it++; //将迭代器指向下一个元素,便不会再死循环了
}
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
int main()
{
string str1 = "123456";
string::iterator it = str1.begin();
string::iterator it2 = str1.begin();
while (it != str1.end())
{
if (*it == '3')
{
it = str1.insert(it, 'i');
it++;
}
cout << *it << " ";
it++;
}
cout << *it2 << endl; //it2这个迭代器有可能会失效,因为在每插入一次时,所有的迭代器都有可能会失效
cout << endl;
return 0;
}
int main()
{
string str1 = "123456";
string::iterator it = str1.begin();
while (it != str1.end())
{
if (*it == '3')
{
it = str1.erase(it);//删除操作后也要重新获取迭代器
}
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
|