const_iterator

使用 const_iterator 类型时,我们可以得到一个迭代器,它自身的值可以
改变,但不能用来改变其所指向的元素的值。可以对迭代器进行自增以及使用解
引用操作符来读取值,但不能对该元素赋值。
不要把 const_iterator 对象与 const 的 iterator 对象混淆起来。声明
一个 const 迭代器时,必须初始化迭代器。一旦被初始化后,就不能改变它的
值:
vector<int> nums(10); // nums is nonconst
const vector<int>::iterator cit = nums.begin();
*cit = 1; // ok: cit can change its underlying element
++cit; // error: can't change the value of cit
 
 
const_iterator 对象可以用于 const vector 或非 const vector,因为不
能改写元素值。const 迭代器这种类型几乎没什么用处:一旦它被初始化后,只
能用它来改写其指向的元素,但不能使它指向任何其他元素。
const vector<int> nines(10, 9); // cannot change elements in nines
// error: cit2 could change the element it refers to and nines is
const
const vector<int>::iterator cit2 = nines.begin();
// ok: it can't change an element value, so it can be used with a
const vector<int>
vector<int>::const_iterator it = nines.begin();
*it = 10; // error: *it is const
++it; // ok: it isn't const so we can change its value
posted @   cnetsa  阅读(507)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示