begin
and end
MembersThe begin
and end
operations (§ 3.4.1, p. 106) yield iterators that refer to the first and one past the last element in the container. These iterators are most often used to form an iterator range that encompasses all the elements in the container.
As shown in Table 9.2 (p. 330), there are several versions of begin
and end
: The versions with an r
return reverse iterators (which we cover in § 10.4.3 (p. 407)). Those that start with a c
return the const
version of the related iterator:
list<string> a = {"Milton", "Shakespeare", "Austen"};
auto it1 = a.begin(); // list<string>::iterator
auto it2 = a.rbegin(); // list<string>::reverse_iterator
auto it3 = a.cbegin(); // list<string>::const_iterator
auto it4 = a.crbegin();// list<string>::const_reverse_iterator
The functions that do not begin with a c
are overloaded. That is, there are actually two members named begin
. One is a const
member (§ 7.1.2, p. 258) that returns the container’s const_iterator
type. The other is nonconst
and returns the container’s iterator
type. Similarly for rbegin
, end
, and rend
. When we call one of these members on a nonconst
object, we get the version that returns iterator
. We get a const
version of the iterators only when we call these functions on a const
object. As with pointers and references to const
, we can convert a plain iterator
to the corresponding const_iterator
, but not vice versa.
The c
versions were introduced by the new standard to support using auto
with begin
and end
functions (§ 2.5.2, p. 68). In the past, we had no choice but to say which type of iterator we want:
// type is explicitly specified
list<string>::iterator it5 = a.begin();
list<string>::const_iterator it6 = a.begin();
// iterator or const_iterator depending on a's type of a
auto it7 = a.begin(); // const_iterator only if a is const
auto it8 = a.cbegin(); // it8 is const_iterator
When we use auto
with begin
or end
, the iterator type we get depends on the container type. How we intend to use the iterator is irrelevant. The c
versions let us get a const_iterator
regardless of the type of the container.