C++11 does allow you to write
const auto p = a.begin();
However, this doesn't do what you want. This makes a regular iterator to non-constant data whose value cannot be changed.
The type of the right-hand side a.begin()
is determined by the type of a
, and not by anything on the left-hand side. If a is non-const, then the non-const version of a.begin()
will be called. So, you could cast a
to a const& and then use it, or you could make a constant reference to a and use that:
const auto& b = a;
auto p = b.begin();
However, a simpler approach would be to use the newly introduced .cbegin() and .cend():
auto p = a.cbegin();