The support for const_iterator in C++98 is not comprehensive enough, and it is quite laborious to use. C++11 has made a great optimization to it, but there are still dead corners, but C++14 has cleared these dead corners, so Now we can use it well.
The first thing we must remember is that in C++11 it is not possible to cast iterator to const_iterator, not even static_cast or reinterpret_cast.
If we want to get a const_iterator type iterator, it is very simple in C++11, just use the object to call its member function cbegin() or cend(). But please note here that C++11 only provides member function versions of cbegin() and cend(), and does not implement non-member versions. Of course, this has been resolved in C++14. We can also implement it ourselves in C++11:
template <class T>
auto cbegin(const T& c) ->decltype(std::begin(c)) {
return std::begin(c);
}
Shorthand
- Const_iterator is preferred over iterator
- In the most common code, the non-member function version of begin(), end(), cbegin(), cend(), etc. are preferred