开发者

calling more than one function in STL algorithm

The classical example using STL algorithms:

void foo(int){};
vector<int> collection;
collection.push_back(3);
collection.push_back(4);
... etc.

std::for_each(collection.begin(), collection.end(), bind(foo, _1));

But what if we have more then one function, which needs to be called with the same argument values:

void bar(int){};
void beer(int){};
... etc.

Repeating for_each algorithm every time with different functions is not option. I 开发者_如何学JAVAneed more elegant solution.


Since you tagged the question with C++11, then you can use lambda as:

std::for_each(collection.begin(), collection.end(), [](int a)
{
   bar(a);    
   beer(a);
});

I recall that C++11 has std::begin and std::end as free functions, which should be preferred over the member functions:

std::for_each(std::begin(collection), std::end(collection), [](int a)
{
   bar(a);    
   beer(a);
});

The rationale why the free functions should be preferred is because now if, for example, you change the type of the collection to simple array (say, int collection[100]), then the above code would work just fine without changing a single character. With the new Standard C++, the free functions are going to be used more uniformly than the member functions.

Or, you can use range-based for loop as:

for(int a : collection)
{
   bar(a);    
   beer(a);
}

Ah! It looks even better. Neat and clean, with no begin and end at all.


This would be a nice place to use lambdas:

#include <vector>
#include <algorithm>

void bar(int){};
void beer(int){};

int main()
{
    std::vector<int> collection;
    collection.push_back(3);
    collection.push_back(4);
    std::for_each(collection.begin(), collection.end(),
                  [](int i) {bar(i); beer(i);});
}


Something like this, perhaps?

void bunch_of_functions( int arg )
{
    foo( arg );
    bar( arg );
    foobar( arg );
}

std::for_each(
    collection.begin(), collection.end()
  , bind(bunch_of_functions, _1)
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜