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.
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.
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.
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