Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::end(myVector) and myVector.end()

I've noticed there are 2 ways to get the end iterator of a vector (or other container class):

std::end(myVector)

and

myVector.end()

The same goes for various other container iterator functions, begin, cend, cbegin, rend, rbegin, crend, crbegin, find, etc. What I'm wondering is if there's any functional difference between these? And if not, is there some historical reason to have both of them?

(Apologies if this is a duplicate, I've searched all over, and found plenty of sources for one or the other of these methods, but none that mentions both or compares the two.)

like image 771
Darrel Hoffman Avatar asked Mar 08 '16 21:03

Darrel Hoffman


People also ask

What is the difference between a begin iterator and an end iterator?

begin: Returns an iterator pointing to the first element in the sequence. cend: Returns a const_iterator pointing to the past-the-end element in the container. end: Returns an iterator pointing to the past-the-end element in the sequence.

What should begin () and end () do for a container?

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

Is vector :: end ()?

vector::end()It is used to return an iterator pointing to the first element in the vector. It is used to return an iterator referring to the past-the-end element in the vector container.

What is difference between delete and delete in C++?

Therefore, erase() is something you can do to an element in a container, remove() is something you can do to a range as it re-arranges that range but doesn't erase anything from the range..


Video Answer


1 Answers

There is a historical reason: before C++11, only the member function versions existed. C++11 added the non-members, which also work for plain C-style arrays, so can be considered to be more general.

int a[] = {3, 1, 5, 67, 28, -12};
std::sort(std::begin(a), std::end(a));

When applied to standard library containers, the effect of std::begin and std::end is to call the container's begin() and end() member functions, so there is no functional difference.

C++14 added std::cbegin, std::cend, std::rbegin, std::rend, std::crbegin and std::crend, with similar behaviour.

like image 166
juanchopanza Avatar answered Sep 20 '22 23:09

juanchopanza