开发者

Member functions comparison as predicates

开发者 https://www.devze.com 2023-03-19 18:01 出处:网络
I have a structure like this. struct A { int someFun() const; int _value; }; I store objects of this structure in a vector.

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 wh开发者_如何学Goose _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> >?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消