本篇学习list迭代器操作
begin:返回指向起始的迭代器
cbegin:返回指向起始的常量迭代器
end:返回指向末尾的迭代器
cend:返回指向末尾的常量迭代器
rbegin:返回指向起始的逆向迭代器
crbegin:返回指向起始的逆向常量迭代器
rend:返回指向末尾的逆向迭代器
crend:返回指向末尾的逆向常量迭代器
代码实现
#include <list> #include <iostream> using namespace std; void getIterator() { list<int> list1 = {23, 35, 39 ,52, 56, 73, 79}; list<int>::iterator it1 = list1.begin(); cout << "list1的值为:"; while (it1 != list1.end()) { cout << *it1 << "\t"; ++it1; } cout << endl; //1.begin:返回指向起始的迭代器 auto begin = list1.begin(); //2.cbegin:返回指向起始的常量迭代器 auto cbegin = list1.cbegin(); cout << "begin = " << *begin << " cbegin = " << *cbegin << endl; *begin = 55; //*cbegin = 66;//常量迭代器不能修改 cout << "begin = " << *begin << " cbegin = " << *cbegin << endl; //3.end:返回指向末尾的迭代器 auto last = --list1.end();//end()是最后一个元素的下一个位置,所以这里要向前移一个位置 //4.cend:返回指向末尾的常量迭代器 auto clast = --list1.cend();//end()是最后一个元素的下一个位置,所以这里要向前移一个位置 cout << "last = " << *last << " clast = " << *clast << endl; cout << "list1的值为:"; auto it2 = list1.begin(); while (it2 != list1.end()) { cout << *it2 << "\t"; ++it2; } cout << endl; //5.rbegin:返回指向起始的逆向迭代器 auto rbegin = list1.rbegin(); //6.crbegin:返回指向起始的逆向常量迭代器 auto crbegin = list1.crbegin(); cout << "rbegin = " << *rbegin << " crbegin = " << *crbegin << endl; *rbegin = 33;//修改最后一个元素的值 //*crbegin = 73;//crbegin返回最后一个常量迭代器,不能修改 cout << "list1的值为:"; for(auto &val: list1) cout << val << "\t"; cout << endl; //7.rend:返回指向末尾的逆向迭代器 auto rend = --list1.rend();//rend返回的是容器第一个元素的前一个位置 //8.crend:返回指向末尾的逆向常量迭代器 auto crend = --list1.crend(); cout << "rend = " << *rend << " crend = " << *crend << endl; *rend = 81; //*crend = 82;//常量迭代器,不能修改 cout << "rend = " << *rend << " crend = " << *crend << endl; cout << "list1的值为:"; for (auto &val: list1) cout << val << "\t"; cout << endl; } int main() { getIterator(); cout << endl; cout << " Hello World!" << endl; return 0; }
讯享网
运行结果:

cbegin, cend, crbegin, crend返回的是常量迭代器,不能通过迭代器修改vector元素的值。这4个函数是C++11里新增加的功能。
参考

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/97294.html