Calling a member function of every element of a C++ vector
c++, function, vector
Solution
Easiest with TR1/C++11:
#include <vector>
#include <functional>
#include <algorithm>
struct Object2{};
struct Object1 {
void foo(Object2*) {}
};
int main() {
std::vector<Object1> vec;
Object2 obj2;
std::for_each(vec.begin(), vec.end(), std::bind(&Object1::foo, std::placeholders::_1, &obj2));
}
But you can also use `std::for_each` with `std::bind2nd`, and `std::mem_fun_ref` if that's not an option:
std::for_each(vec.begin(), vec.end(), std::bind2nd(std::mem_fun_ref(&Object1::foo), &obj2));
Problem
Suppose there is a vector of class objects. ``` vector<Object1> vec; ``` Say, `Object1` has a member function `void foo(Object2*)`. I want to do the following: ``` for(int i=0; i<vec.size(); i++) { vec[i].foo(obj2); } ``` How can this be done without using an explicit loop?