I\'m wondering why the STL doesn\'t overload their algorithm functions such that I can call them by simply providing a container and not taking the more verbose way to pass
To understand that I think one must have to understand the philosophy of C++ algorithms. Lets ask this question first:
Why C++ algorithms are implemented as free functions instead of member functions?
Well the answer is pretty much simple : to avoid implementation explosions. Suppose you have M
containers and N
algorithms, and if you implement them as members of the containers, then there will be M*N
implementations. There are two (related) problems in this approach:
C++ solves these issues by implementing them as free functions, so that you have only N
implementations. Each of the algorithm that operates on a container takes a pair of iterators, that defines the range. If you want overloads that take container, instead of pair of iterators, then the Standard have to provide such overloads for each of the algorithm, and there will be 2*N
implementations which pretty much defeat the very purpose why C++ has separated the algorithms from the containers in the first place, and half of these functions don't do anything which cannot be done by the other half.
So I don't think it is that much an issue. Just to avoid one single argument, why implement N
more functions (which also impose some restriction on its usage such as you cannot pass pointers to it)? However, if programmers want such functions in their utility, they can implement them anytime along with many others based on the Standard algorithm!
You commented:
Well, the 2*N implementations are in fact only N implementations. The other N ones are inlined overloads which directly call the "real" version of the algorithm, so they are a header-only thing. Providing container overloads doesn't defeat the purpose to separate algorithms from containers, as (as you can see in my example) they can use templates to handle all types of containers.
Based on this logic, one can very well argue for M*N
algorithms. So make them member functions too (and call the free functions internally)? I'm sure many OOP guys would prefer
auto result = container.accumulate(val);
over
auto result = std::accumulate(container.begin(), container.end(), val);