4

I want to observe the difference between cbegin and begin.

But when i use cbegin i am getting the same result as begin. According to definition cbegin will return const itertaor and we cant modify the element using the const iterator returned by cbegin. But, still i am able to erase the element at particular position.

    for (auto i = g1.cbegin(); i != g1.cend(); ++i){             
            cout << *i << " ";
    }
    //below code erases element at const pointer
    g1.erase(i);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    As I understand it it means only you cannot change the value of the item the iterator points to but you still can modify the container (aka erasing) – Philipp Sep 13 '19 at 12:08

2 Answers2

6

The member function erase accepts const_iterator(s).

For example

iterator erase(const_iterator position);

In early Standards the function indeed was declared with non-constant iterators.

Take into account that the function returns a non-constant iterator but it can be converted implicitly to a constant iterator and can be compared with constant iterators.

By the way this call

g1.erase(i);

erases nothing because after the loop i is equal to the iterator returned by the function cend provided that the name i is defined before the loop.

auto i = g1.cbegin();
for (; i != g1.cend(); ++i){             
        cout << *i << " ";
}
//below code erases element at const pointer
g1.erase(i);

You can erase an element of the vector using the const_iterator because the vector itself is not constant. If the vector would be constant you could not erase its element.

That is the erase member function changes the vector itself (so it may not be applied to a constant vector), but it does not change elements of the vector using the const_iterator.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Thanks a lot Vlad from Moscow.

I just tried *i=3; in the loop where i am using cend and cbegin.

for (auto it = g1.cbegin(); it != g1.cend(); ++it){

            cout << *it << " ";

           *it=3;       

    }

I got compilation error : error: assignment of read-only location β€˜it.__gnu_cxx::__normal_iterator >::operator*()’ *it=3; ^