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?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With