vector学习之迭代器begin, end, cbegin, cend, rbegin, rend, rcbegin, rcend

vector提供的迭代器有以下几种访问方式

begin, cbegin返回指向超始的迭代器

end,cend返回指向末尾的迭代器

rbegin,crbegin返回指向超始的逆向迭代器

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

代码示例如下:

#include 
#include 

using namespace std;

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

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

int main()
{
    //int = [-2147483648, 2147483647]

    getIterator();
    cout << endl;
   
    cout << "Hello World!" << endl;
    return 0;
}

运行结果:

vector学习之迭代器begin, end, cbegin, cend, rbegin, rend, rcbegin, rcend_第1张图片

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

 

 

 

 

 

你可能感兴趣的:(STL,vector)