Call participant function for each item in the container

This question is a style question as you can always write a for loop or something similar; however, is there a less intrusive equivalent of STL or BOOST to write:

for (container<type>::iterator iter = cointainer.begin(); iter != cointainer.end(); iter++) iter->func(); 

?

Something like (imaginary):

 call_for_each(container.begin(), container.end(), &Type::func); 

I think it would be 1) less typing, 2) easier to read, 3) fewer changes if you decide to change the type of the base type / container type.

EDIT: Thanks for your help, now, what if I wanted to pass some arguments to a member function?

+8
c ++ boost coding-style stl
source share
5 answers

I found out that boost bind seems to work well for the task, plus you can pass extra arguments to the method:

 #include <iostream> #include <functional> #include <boost/bind.hpp> #include <vector> #include <algorithm> struct Foo { Foo(int value) : value_(value) { } void func(int value) { std::cout << "member = " << value_ << " argument = " << value << std::endl; } private: int value_; }; int main() { std::vector<Foo> foo_vector; for (int i = 0; i < 5; i++) foo_vector.push_back(Foo(i)); std::for_each(foo_vector.begin(), foo_vector.end(), boost::bind(&Foo::func, _1, 1)); } 
+4
source share
  #include <algorithm> // for_each #include <functional> // bind // ... std::for_each(container.begin(), container.end(), std::bind(&Type::func)); 

See std::for_each and std::bind more details.

Skipped your editing: In any case, here is another way to achieve what you want, without using Boost, if necessary:

 std::for_each(foo_vector.begin(), foo_vector.end(), std::bind(&Foo::func, std::placeholders::_1)); 
+23
source share

You can use std :: for_each or force the foreach construct .

Use boost BOOST_FOREACH or BOOST_REVERSE_FOREACH when you do not want to translate logic into another function.

+5
source share

If you really want to improve performance, and not just make your code, then you really need a map function. Eric Sink wrote .NET implementation

0
source share

Starting with the C ++ 11 standard, the BOOST approach is standardized with another syntax as a "range-based loop":

 class Foo { Foo(int x); void foo(); } vector<int> list = {Foo(1),Foo(2),Foo(3)}; for(auto &item: list) item.foo(); 
0
source share

All Articles