Why is the "start / end" compared to the "first / last" mismatch?

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

For example:

Edit: An even greater discrepancy is found. These are not just algorithms that use " first / last ", they are also container constructors (for example, vector(first, last, ...) ).

I did not check all the containers and algorithms, but I checked a few more and all the containers offered by begin / end , and all the algorithms wanted first / last (or options like first1 and first2 ).

Is there a good reason for this? It would be more reasonable for me if they all used the same thing. begin and end preferable, since I don't like last because it sounds inclusive, but it doesn't. For algorithms, this simply means the beginning and end of the range that will be processed, just like the first and last average.

+7
c ++
source share
3 answers

The reason may be historical: this is what they called Stepanov and Lee, the first STL developers who later turned into the standard C ++ library.

Here is an article by Stepanov about STL . Page 47 describes sorting

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

Page 19 describes the container operations begin() and end() .

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

+7
source share

first and last can be any two iterators, while last not "before" first . They should not be the beginning and end of the container.

+10
source share

IMHO, it would be even more confusing if containers and algorithms called them the same. The whole point of algorithms that accept iterators is that they should not be begin and end container, but they can be any iterators. The presence of different names on the interfaces is underlined by the fact that you, as a user, are responsible for passing a significant pair of the first and last tags.

On the other hand, this is the weak point of the algorithms that they do not offer methods that take the container as a parameter, when in most cases you just want the algorithm to work from begin to end iterator.

+4
source share

All Articles