The member begin has two overloadings one of them is const_iterator begin() const;
. There\'s also the cbegin const_iterator cbegin() const noexcept;
begin
will return an iterator
or a const_iterator
depending on the const-qualification of the object it is called on.
cbegin
will return a const_iterator
unconditionally.
std::vector<int> vec;
const std::vector<int> const_vec;
vec.begin(); //iterator
vec.cbegin(); //const_iterator
const_vec.begin(); //const_iterator
const_vec.cbegin(); //const_iterator
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<int> v{10,20,30,40,50};
vector<int> :: 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.