signed

QiShunwang

“诚信为本、客户至上”

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

2021/3/21 1:01:29   来源:

本篇学习deque的迭代器操作:

begin:返回指向起始的迭代器

cbegin:返回指向起始的迭代器

end:返回指向末尾的迭代器

cend:返回指向末尾的迭代器

rbegin:返回指向起始的逆向迭代器

crbegin:返回指向起始的逆向迭代器

rend:返回指向末尾的逆向迭代器

crend:返回指向末尾的逆向迭代器

代码实现

#include <deque>
#include <iostream>

using namespace std;

void getIterator()
{
    deque<int> deque1 = {12, 32, 34 ,53, 56, 76, 78};
    deque<int>::iterator it1 = deque1.begin();
    while (it1 != deque1.end())
    {
        cout << *it1 << "\t";
        ++it1;
    }
    cout << endl;
    auto begin = deque1.begin();
    auto last = deque1.end() - 1;//end()是最后一个元素的下一个位置,所以这里要向前移一个位置
    *begin = 55;
    cout << "begin c= " << *begin << " end  = " << *last << endl;
    auto it2 = deque1.begin();
    while (it2 != deque1.end())
    {
        cout << *it2 << "\t";
        ++it2;
    }
    cout << endl;
    auto cbegin = deque1.cbegin();
    auto cend = deque1.cend() - 1;
    //*cbegin = 88;//cbegin返回的是一个常量迭代器,不能修改他的值
    cout << "cbegin = " << *cbegin << " cend = " << *cend << endl;
    cout << endl;

    auto rbegin = deque1.rbegin();
    auto rend = deque1.rend() - 1;//rend返回的是容器第一个元素的前一个位置
    cout << "rbegin = " << *rbegin << " rend = " << *rend << endl;
    *rbegin = 98;//修改最后一个元素的值
    auto it3 = deque1.begin();
    while (it3 != deque1.end())
    {
        cout << *it3 << "\t";
        ++it3;
    }
    cout << endl;
    auto crbegin = deque1.crbegin();
    auto crend = deque1.crend() - 1;
    //*crbegin = 73;//crbegin返回最后一个常量迭代器,不能修改
    cout << "crbegin = " << *crbegin << " crend = " << *crend << endl;

    cout << endl;
}

int main()
{
    getIterator();
    cout << endl;

    cout << "Hello World!" << endl;
    return 0;
}

运行结果:

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

参考:

https://zh.cppreference.com/w/cpp/container/deque