Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the "begin/end" vs "first/last" discrepancy? [closed]

Tags:

c++

Why do containers offer "begin"/"end" iterators while algorithms want "first"/"last" iterators?

For example:

  • vector offers .begin() and .end() (cppreference.com, cplusplus.com).

  • sort wants parameters first and last (cppreference.com, cplusplus.com).

Edit: Found an even bigger discrepancy. It's not just algorithms that use "first/last", it's also container constructors (like vector(first, last, ...)).

I didn't check all containers and algorithms, but did check a few more and all containers offered begin/end and all algorithms wanted first/last (or variations like first1 and first2).

Is there a good reason for this? To me it would make more sense if they all used the same. Preferably begin and end, as I dislike last because that sounds inclusive but isn't. For algorithms it would simply mean the begin and end of the range to be processed, just like what first and last mean now.

like image 482
Stefan Pochmann Avatar asked Feb 12 '17 10:02

Stefan Pochmann


2 Answers

first and last can be any two iterators as long as last is not "before" first. They do not have to be the beginning and ending of a container.

like image 99
Code-Apprentice Avatar answered Oct 13 '22 19:10

Code-Apprentice


The reason is likely to be historical: this is what they were called by Stepanov and Lee, first implementers of STL, which later evolved into C++ Standard Library.

Here is Stepanov's paper on STL. Page 47 describes sort

template <class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last);

Page 19 describes containers' operations begin() and end().

Note that in addition to begin/first and end/last C++ Standard Library describes optional sequence operations front() and back(). The difference in naming is easy to understand here, because the operations must be available on the same container, and back() is inclusive.

like image 39
Sergey Kalinichenko Avatar answered Oct 13 '22 18:10

Sergey Kalinichenko