In C++ library arrays, what are some cases where it's useful to have the .begin()
and .end()
member functions?
On cplusplus.com, the example use is to iterate through an array:
for ( auto it = myarray.begin(); it != myarray.end(); ++it )
But
for (int i = 0; i < myarray.size(); i++)
can be used for that.
begin()
and end()
return iterators. Iterators provide uniform syntax to access different types of containers. At the first glance they might look like an overkill for traversing a simple array, but consider that you could write the same code to traverse a list, or a map.
This uniform access to various containers will allow you to write algorithms that work on all of them without knowing their internal structure. A for loop from begin to end is just a first piece in a much larger mosaic. Just look up the list of standard algorithms to appreciate the power of this simple abstraction.