For example:
v.for_each([](int i) { printf("%d\n", i); });
if far more elegant and readable than the commonly-used:
std::for_each(v.begin(), v.end(), [](int i) { printf("%d\n", i); });
Is there a legitimate reason such a member function is missing from the standard?
This is the standard design rationale for the entire library: Separate containers from algorithms.
If you did it your way, you'd have to implement every feature X for every container Y, leading you to M * N implementations if you have M features and N containers.
By using iterators and make algorithms work on iterators rather than containers, you only have to implement M algorithms plus N iterator interfaces.
This separation also means that you have infinitely wider scope of application: the algorithms cannot just be used for every library container, but for any container, present or future, that anyone decides to write and equip with iterators. Finite vs infinite reuse is quite a strong argument! And calling the algorithms through the generic, free interface doesn't add any cost.
template <class InputIterator, class UnaryFunction>
UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f);
As you can see for_each takes Input Iterator as in parameter, so any stl container that can provide a input iterator compatible(meaning apart from input iterator, it could also be bidirectional ,random access iterator etc) would be compatible with std::for_each. By designing this way, stl generic separate algorithm from data type(containers) which is more elegant & generic.
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