list学习之迭代器begin, cbegin, end, cend, rbegin, crbegin, rend, crend

本篇学习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里新增加的功能。

参考

http://www.cplusplus.com/reference/list/list/
https://zh.cppreference.com/w/cpp/container/list

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值