90

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?

Brickgao
  • 35
  • 4
user3663882
  • 6,957
  • 10
  • 51
  • 92

2 Answers2

124

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
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • 7
    That's it? So in fact, we have two functions behaving completely the same on const objects... Does it reslly make a sense? – user3663882 Jul 03 '15 at 14:04
  • 6
    It's for flexibility. If you know you need a `const_iterator`, call `cbegin`. If you know you need an `iterator`, call `begin` and you'll get an error if it's not valid. If you don't care, call `begin`. – TartanLlama Jul 03 '15 at 14:06
  • 2
    @user3663882: See http://stackoverflow.com/questions/12001410/what-is-the-reason-behind-cbegin-cend – Christian Hackl Jul 03 '15 at 14:10
  • What is the difference between `const_iterator` and `iterator` –  Aug 17 '19 at 17:47
  • 1
    @Asadefa - check out the answer [here](https://stackoverflow.com/a/309589/11265473) – clk May 22 '20 at 23:31
32

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;
}
Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
heapster
  • 459
  • 1
  • 5
  • 7
  • The second code is not producing error. It is working fine i tried it. – Proton Mar 09 '21 at 05:35
  • @Proton I does not compile. It must and will fail at the assignment operator as it can not have a semantically valid overload for anything `const`. – lopho Mar 10 '21 at 15:42