最近研究iterator,看了下const_iterator和const iterator的使用,记录下来,以供以后参考。
(1)iterator迭代器,对容器中的元素可以读写操作
string tem = "abcde";
string::iterator start = tem.begin();
string::iterator end = tem.end();
while(start != end)
{
*start = 'a';
++start;
}
cout<<tem<<endl;输出结果:
(2)const_iterator,对容器中的元素只能读,不能写
string tem = "abcde";
string::const_iterator start = tem.begin();
string::const_iterator end = tem.end();
while(start != end)
{
*start = 'a';
++start;
}
cout<<tem<<endl;程序出错,如下:
注意:如果容器是一个const类型的,则只能用const_iterator,不能用iterator
const string tem = "abcde";
string::const_iterator start = tem.begin();
string::const_iterator end = tem.end();
while(start != end)
{
cout<<*start<<endl;
++start;
}输出结果:
(3)const iterator:迭代器指向一块固定内存,不能指向其它内存块,但是该内存块的存储内容可变
string tem = "abcde";
const string::iterator start = tem.begin();
*start = 'b';
cout<<*start<<endl;输出结果:
尝试使该迭代器指向其它内存,会报错:
string tem = "abcde";
const string::iterator start = tem.begin();
start++;
cout<<*start<<endl;出错:
本文详细介绍了C++中iterator、const_iterator及constiterator的区别与使用场景。iterator允许读写容器元素;const_iterator只允许读取;而constiterator则锁定迭代器指向的内存位置但允许修改内存内容。
610

被折叠的 条评论
为什么被折叠?



