Calling a member function of each element of a C ++ vector

Suppose that there is a vector of class objects.

vector<Object1> vec;

Say it Object1has 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?

+5
source share
3 answers

The 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_eachwith std::bind2ndand std::mem_fun_ref, if this is not an option:

std::for_each(vec.begin(), vec.end(), std::bind2nd(std::mem_fun_ref(&Object1::foo), &obj2));
+6
source

One older style is the manual notation of a functor. For more complex logic, this allows you to select a whole class for the problem.

class fancyFunctor
{
  Object2* m_data;

public:
  fancyFunctor(Object2 * data) : m_data(data){}

  operator()(Object1 & ref) 
  {
    ref.foo(m_data) 
  }
}

Then for iteration:

std::for_each(vec.begin(),vec.end(), fancyFunctor(&randomObject2));
0
source

Reading such code is not perfect, and it cannot be done in a simple, simple way. This is because the first argument of a member method of a class is a pointer to the object of this class on which it will be executed.

Alternatively, you can use the foreach loop that comes with the new C ++ 11 standard (but this is still a loop).

-1
source

All Articles