Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 968
vikaspraj Avatar asked May 09 '12 13:05

vikaspraj


People also ask

How do you count the number of occurrences of an element in a vector in C++?

std::count() returns number of occurrences of an element in a given range. Returns the number of elements in the range [first,last) that compare equal to val.


1 Answers

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));
like image 70
Flexo Avatar answered Nov 04 '22 13:11

Flexo