Why did the CPP standard library container add cbegin and cend methods?

the standard library container before CPP11 overloaded constant and non-constant object versions for begin and end, and defined cbegin and cend for constant version lines in 11.

11 what is the point of doing this, that is, what is the advantage of such a design compared to before 11?

Mar.07,2021

cbegin and cend are added at the beginning of cPP14 , and are not cPP11

.

TL;DR, is a more convenient way to obtain constant iterators.
before cPP14, you wanted to get a constant iterator, and the method was more complicated:

typedef vector<MyType> vect;
typedef vect::const_iterator c_iter;
vect v;
// alternatives:
c_iter it = const_cast<vect const &>(v).begin(); // 1
c_iter it = static_cast<c_iter>( v.begin() ); // 2 (explicit)
c_iter it = v.begin(); // 2 (implicit)

it is true that is used in const, but you still need to use it when you use it, such as fold , or its equivalents in cPP. std::accumulate does not need to be modified by the member pointed to by the iterator, so const-qualify is reasonable.

moreover, its implementation is also very simple. It is easy to use the existing facilities and will not break core laungage:

.
const_iterator cbegin() const;
const_iterator cend () const;
Finally, it works with other features of cPP0x, such as auto/decltype, and increases its power exponentially, for example, if there is no cbegin, auto, you can only get a non-const version.

the best way to solve this problem is to go to wg21 to see its proposal in 2004, http://www.open-std.org/jtc1/.

.

Update:

I'll tell you. Before the release of cPP14, some people complained that there was no const version of std::begin () , and then Uncle Cao took the stage.

Menu