balki
balki

Reputation: 27664

Member functions comparison as predicates

I have a structure like this.

struct A
{
  int someFun() const;
  int _value;
};

I store objects of this structure in a vector.

  1. How to find the object whose member someFun() returns 42?

  2. How to find the object whose _value is 42?

I guess I have to use the combination of bind and equal_to, but I'm not able to find the right syntax.

vector<A> va;
vector<A>::const_iterator val = find_if(va.begin(),va.end(),boost::bind(???,42));

Edit:

Thanks. But one more doubt.

What if I had vector<A*> or vector<boost::shared_ptr<A> >?

Upvotes: 3

Views: 475

Answers (1)

Luc Danton
Luc Danton

Reputation: 35449

vector<A> va;

vector<A>::const_iterator v0 = find_if(
    va.begin()
    , va.end()
    , boost::bind(&A::someFun, _1) == 42 );

vector<A>::const_iterator v1 = find_if(
    va.begin()
    , va.end()
    , boost::bind(&A::_value, _1) == 42 );

In case you do need to compose bind expressions (e.g. using a functor that cannot be expressed with the operators supported by boost::bind):

vector<A>::const_iterator v1 = find_if(
    va.begin()
    , va.end()
    , boost::bind(functor(), boost::bind(&A::someFun, _1), 42) );

which results in a call to functor::operator() with arguments as follow: the result of calling the member on the argument to the bind expression, and 42.

Upvotes: 4

Related Questions