Why do STL algorithms require two iterators explicitly?

Viewed 147

Several algorithms in the C++ STL require to specify explicitly two iterators. For example, sorting a std::vector<T> v is done with std::sort(v.begin(), v.end()). Since processing the entire container (e.g. with std::sort, std::find, etc.) is a fairly common situation, I'm wondering why a simple version of these algorithms that accepts just the container is not implemented. I mean something like std::sort(v), that uses v.begin() and v.end() iterators by default.

Is there some underlying technical reason that I'm not aware of? Thank you in advance.

1 Answers

I'm wondering why a simple version of these algorithms that accepts just the container is not implemented.

It was, in C++20, with std::ranges versions.

Is there some underlying technical reason that I'm not aware of?

Sort of. When the algorithms in <algorithm> were first proposed, distinguishing between different cases in templates was possible, but it was rather unwieldy.

How do you distinguish, from the call site, which of these templates fits?

template <typename InIt, typename OutIt, typename Func>
OutIt transform(InIt, InIt, OutIt, Func); // unary transform on iterator

template <typename Lhs, typename Rhs, typename OutIt, typename Func>
OutIt transform(Lhs, Rhs, OutIt, Func); // binary transform on containers
Related