What is the difference between cbegin and begin for vector?

前端 未结 2 366
天命终不由人
天命终不由人 2020-12-23 09:33

The member begin has two overloadings one of them is const_iterator begin() const;. There\'s also the cbegin const_iterator cbegin() const noexcept;

2条回答
  •  旧时难觅i
    2020-12-23 10:14

    begin() returns the iterator to beginning while cbegin() returns const_iterator to beginning. Basic difference between these two is iterator (i.e begin()) lets you change the value of object it is pointing to and const_iterator will not let you change the value of the object.

    For example:

    vector v{10,20,30,40,50};
    vector :: iterator it;
    
    for(it = v.begin(); it != v.end(); it++)
    {
    *it = *it - 10;
    }
    

    This is allowed. Vector Values changes to {0,10,20,30,40}

    for(it = v.cbegin();it != v.cend();it++)
    {
     *it = *it -10;
    }
    

    This is not allowed. It will throw error.

提交回复
热议问题