Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a for_each member function for each collection type in stl?

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?

like image 300
Benjamin Nitlehoo Avatar asked Sep 03 '11 11:09

Benjamin Nitlehoo


2 Answers

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.

like image 97
Kerrek SB Avatar answered Nov 04 '22 12:11

Kerrek SB


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.

like image 40
RoundPi Avatar answered Nov 04 '22 12:11

RoundPi