15

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.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
milennalim
  • 309
  • 1
  • 8

4 Answers4

26

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.

Maksim Solovjov
  • 3,147
  • 18
  • 28
10

The whole point of standard containers is the ability to change them and use the same syntax. If you had a linked list, the first syntax still works.

Also it is equivalent to a pointer. i is an index so myarray[i] is slightly slower than it.

Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30
  • 2
    ... and, more importantly, having the same syntax for iteration over the container means you can write a template that will work for any of them. – Jules Aug 20 '15 at 22:08
  • Most who care point to negligible difference. http://stackoverflow.com/questions/2524233/speed-accessing-a-stdvector-by-iterator-vs-by-operator-index – Robert Jacobs Aug 21 '15 at 13:11
7

In addition to be generic with other containers, begin, end is useful for for range

for (const auto& e : myarray)
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

Now try iterating through a linked list. The only efficient way is to iterate from one item to the next, until you reach the end.

Graham
  • 1,655
  • 9
  • 19