milennalim
milennalim

Reputation: 309

Whats the point of .begin() and .end()?

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.

Upvotes: 15

Views: 3218

Answers (4)

Graham
Graham

Reputation: 1705

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.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217255

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

for (const auto& e : myarray)

Upvotes: 7

Maksim Solovjov
Maksim Solovjov

Reputation: 3157

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.

Upvotes: 26

Robert Jacobs
Robert Jacobs

Reputation: 3360

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.

Upvotes: 10

Related Questions