tags:

views:

198

answers:

3

Hello!

Consider following example:

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

#include <boost/bind.hpp>

const int num = 3;

class foo {
private:
    int x;
public:
    foo(): x(0) {}
    foo(int xx): x(xx) {}
    ~foo() {}
    bool is_equal(int xx) const {
        return (x == xx);
    }
    void print() {
        std::cout << "x = " << x << std::endl;
    }
};

typedef std::vector<foo> foo_vect;

int
main() {
    foo_vect fvect;
    for (int i = -num; i < num; i++) {
        fvect.push_back(foo(i));
    }
    foo_vect::iterator found;
    found = std::find_if(fvect.begin(), fvect.end(),
        boost::bind(&foo::is_equal, _1, 0));
    if (found != fvect.end()) {
        found->print();
    }
    return 0;
}

Is there a way to use some sort of negator adaptor with foo::is_equal() to find first non zero element. I don't want to write foo::is_not_equal(int) method, I believe there is a better way. I tried to play with std::not2, but without success.

+2  A: 

The argument to std::not2 needs to look like a 'normal' binary predicate, so you need to adapt foo::is_equal with something like std::mem_fun_ref. You should be able to do something like:

std::not2(std::mem_fun_ref(&foo::is_equal))
Charles Bailey
+3  A: 

Since you're using Boost.Bind:

std::find_if(fvect.begin(), fvect.end(),
    !boost::bind(&foo::is_equal, _1, 0)
);

(Note the "!")

Éric Malenfant
+2  A: 

If you are using unary functors (in the STL sense) you can use std::not1:

struct odd : public std::unary_function<int,bool>
{
   bool operator()( int data ) const {
      return data % 2;
   }
};
void f( std::vector<int> const & v )
{
   std::vector<int>::const_iterator first_odd
        = std::find_if( v.begin(), v.end(), odd() );
   std::vector<int>::const_iterator first_even 
        = std::find_if( v.begin(), v.end(), std::not1( odd() ) );
}

But that does not work with the *unspecified_type* that is returned from boost::bind. For that you can use, as Éric already posted, the ! operator over the *unspecified_type* returned.

David Rodríguez - dribeas