Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 945
milennalim Avatar asked Aug 20 '15 18:08

milennalim


People also ask

What does begin do in c++?

Introduction to C++ begin() This C++ begin() is used to get the iterator pointing to the initial element of the map container. This pointer is bidirectional since it can be moved to either directions in the sequence.

What is iterator begin?

begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container.


1 Answers

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.

like image 142
Maksim Solovjov Avatar answered Sep 21 '22 17:09

Maksim Solovjov