how to use non-static member function as comparision function infind_if?

J

John Black

Hi,
In using find_if() you need to name a comparision function which
normally is a static function, but sometimes it is really inconvinient
for this, let's take this example,

class MyClass{
vector<int> myVec;
void func();
};

When MyClass::func() needs to call find_if against myVec, I have to
decalre a static function for it, but myVec is not static, it can not be
referenced in static function, then I have to consider convert myVec to
static...

Looks like I miss something in between, there should be some way to do
this.

Thanks.
 
D

Daniel T.

John Black <[email protected]> said:
Hi,
In using find_if() you need to name a comparision function which
normally is a static function, but sometimes it is really inconvinient
for this, let's take this example,

class MyClass{
vector<int> myVec;
void func();
};

When MyClass::func() needs to call find_if against myVec, I have to
decalre a static function for it, but myVec is not static, it can not be
referenced in static function, then I have to consider convert myVec to
static...

Looks like I miss something in between, there should be some way to do
this.

Thanks.

I'm not sure what you are having a prblem with here. find_if does not
need any static function to work, nor does it use a comparison function,
(rather it uses a predicate function.)

Let's say you need to find an item in myVec that is greater than 5:

struct MyClass {
vector<int> myVec;
void func() {
vector<int>::iterator it =
find_if( myVec.begin(), myVec.end(),
bind2nd( greater<int>(), 5 ) );
assert( it == myVec.end() || *it > 5 );
}
};

Or are you complaining because you want to use func as the predicate?

class MyClass {
vector<int> myVec;
bool func( int x ) {
return x > 5;
}
void check() {
vector<int>::iterator it =
find_if( myVec.begin(), myVec.end(),
bind1st( mem_fun( &MyClass::func ), this ) );
assert( it == myVec.end() || *it > 5 );
}
};

Maybe if you explained better what you are wanting to do?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top