C++ Primer学习7:const iterator与const_iterator的区别

const iterator是指iterator是参量,不可修改

const_iterator是iterator指向的元素不可修改

#include 
#include 
using namespace std;

int main()
{

    vector num(10,9);
    //对比下面2个迭代器
    const vector::iterator iter1 = num.begin(); //常量迭代器,该迭代器不能改变
//    ++iter1; //error

    vector::const_iterator iter2 = num.begin();  //该迭代器所指向的元素的值不能改变
    ++iter2; //true
//    *iter2 = 7;  //error


    int i;
    vector::iterator iter;
    for(i = 0,iter = num.begin(); iter != num.end(); ++iter,++i)
    {
        *iter = i;
    }

    //迭代器的算术运算
    //iter + n
    vector::iterator iter3 = num.begin();
    vector::iterator iter4 = num.end();
    vector::iterator mid = num.begin() + num.size() / 2;
    iter3 += 2;
    cout << "*iter3 = " << *iter3 << endl;
    cout << "iter4到iter3的距离:"<< iter4 - iter3 <


你可能感兴趣的:(c++,const,iterator,const_itreator)