Why is there no for_each member function for each type of collection in stl?

For instance:

v.for_each([](int i) { printf("%d\n", i); }); 

if it is more elegant and readable than commonly used:

std::for_each(v.begin(), v.end(), [](int i) { printf("%d\n", i); });

Is there a legitimate reason why such a member function is missing from the standard?

+5
source share
4 answers

This is the standard design rationale for the entire library: separate containers from algorithms.

If you did this in your own way, you will need to implement each function X for each container Y, which will lead you to implementations of M * N, if you have M-functions and N containers.

, , M N .

, : , , , . - ! , .

+8
template <class InputIterator, class UnaryFunction>
UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f);

, for_each Input Iterator , stl-, , ( , -, , ..), std:: . , stl (), .

+2

, , , , , , CRTP-, . , , , .

, . , , .

+1

?

Member functions only serve if the implementation can be more efficient (set :: find is more efficient than std :: find () in the set).

PS Oh, and if you want to avoid the ubiquitous calls .begin(), en .end(), use Boost Range Algorithms . Sweet syntactic sugar

Random pattern inspired by gain range:

#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/pending/integer_range.hpp>

using namespace boost::adaptors;

static int mod7(int v) 
    { return v % 7; }

int main() 
{
    std::vector<int> v;

    boost::copy(
            boost::make_integer_range(1,100) | transformed(mod7), 
            std::back_inserter(v));

    boost::sort(v);

    boost::copy(
            v | reversed | uniqued, 
            std::ostream_iterator<int>(std::cout, ", "));
}
0
source

All Articles