What is the difference between cbegin and begin for vector?

C++VectorStlIterator

C++ Problem Overview


The member begin has two overloadings one of them is const_iterator begin() const;. There's also the cbegin const_iterator cbegin() const noexcept;. Both of them returns const_iterator to the begin of a list. What's the difference?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

begin() returns an iterator to beginning while cbegin() returns a const_iterator to beginning.

The basic difference between these two is iterator (i.e begin()) lets you change the value of the object it is pointing to and const_iterator will not let you change the value of the object.

For example:

This IS allowed. The vector values change to {0,10,20,30,40}:

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 NOT allowed. It will throw an error:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3663882View Question on Stackoverflow
Solution 1 - C++TartanLlamaView Answer on Stackoverflow
Solution 2 - C++heapsterView Answer on Stackoverflow