Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ select from a vector of objects

Tags:

c++

lambda

stl

I have a class A with the following member method:

bool A::test();

I have a vector<A> v of A objects. I would like to create a new vector<A> from v, selecting only those elements for which A::test() returns true.

What is the simplest and most elegant way to do this using STL and boost::lambda (I do not have C++11) ?

like image 251
user231536 Avatar asked May 22 '26 19:05

user231536


1 Answers

While copy_if didn't make it into the earlier standard, you can accomplish the same thing with remove_copy_if.

And if you have C++11 available, it's trivially simple:

std::remove_copy_if(
      v.begin(),
      v.end(),
      std::back_inserter(b),
      [] (const A& val) -> bool
      { return val.test(); });

Since you don't have C++11, still easy:

// global free function
bool test_a(const A& a) { return a.test(); }

std::remove_copy_if(
      v.begin(),
      v.end(),
      std::back_inserter(b),
      test_a);
like image 66
Chad Avatar answered May 24 '26 09:05

Chad