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.)
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.
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.
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.
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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With