What is the reason behind cbegin/cend?

Viewed 54461

I wonder why cbegin and cend were introduced in C++11?

What are cases when calling these methods makes a difference from const overloads of begin and end?

7 Answers

its simple, cbegin returns a constant iterator where begin returns just an iterator

for better understanding lets take two scenarios here

scenario - 1 :

#include <iostream>
using namespace std;
#include <vector>
int main(int argc, char const *argv[])
{
std::vector<int> v;

for (int i = 1; i < 6; ++i)
{
    /* code */
    v.push_back(i);
}

for(auto i = v.begin();i< v.end();i++){
    *i = *i + 5;
}

for (auto i = v.begin();i < v.end();i++){
    cout<<*i<<" ";
}

return 0;
}

this will run because here iterator i is not constant and can be incremented by 5

now let's use cbegin and cend denoting them as constant iterators scenario - 2 :

#include <iostream>
using namespace std;
#include <vector>
int main(int argc, char const *argv[])
{
std::vector<int> v;

for (int i = 1; i < 6; ++i)
{
    /* code */
    v.push_back(i);
}

for(auto i = v.cbegin();i< v.cend();i++){
    *i = *i + 5;
}

for (auto i = v.begin();i < v.end();i++){
    cout<<*i<<" ";
}

return 0;
}

this is not going to work, because you cant update the value using cbegin and cend which returns the constant iterator

Related