
using greater<> on an object
I think you'll want to use find_if. It takes a predicate as the third argument.
Use find if you want to find the first element that is equal to the third argument.
Also, defining a conversion operator (CMyClass::operator int()) allows greater<int> () to do the comparison.
Example:
using namespace std;
class CMyClass
{
public:
CMyClass(int arg = 0)
{
x = arg;
}
operator int() const {return x;}
int x;
private:
string strWhatever;
Quote:
};
int main(int argc, char* argv[], char* envp[])
{
list<CMyClass> mylist;
mylist.push_back(CMyClass(0));
mylist.push_back(CMyClass(3));
mylist.push_back(CMyClass(4));
list<CMyClass>::iterator it;
it = find_if(mylist.begin(), mylist.end(),bind2nd(greater<int>(), 3));
if(it != mylist.end())
printf("using find_if it->x = %i\n", it->x);
else
printf("using find_if not found\n");
it = find(mylist.begin(), mylist.end(),CMyClass(3));
if(it != mylist.end())
printf("using find it->x = %i\n", it->x);
else
printf("using find not found\n");
return 0;
Quote:
}
> Hey all,
> I want to find the first object in a list that has a value greater than
> another one, but the value is inside an object. Using the Josuttis book as a
> reference, I've tried variations of:
> class CMyClass
> {
> public:
> int x;
> string strWhatever;
> };
> std::list<CMyClass>::iterator it
> it = find(mylist.begin(), mylist.end(), bind2nd(greater<CMyClass>, 3));
> Okay, I know this won't compile, but the problem is, I can't find any
> suitable solution to get greater to look inside the object of CMyClass and
> compare with 3. Using the compiler errors as hints, I've tried adding the
> ==, (), and < operators, all giving me various other errors, typically
> ending up in the greater() or find() functions.
> I've tried writing my own Unary and Binary Compose Function Object Adapters
> (whew), but no success there either. To be honest, my lack of detail here
> basically means I have no idea what I'm doing here, and while the book is
> very very good, in this section, it uses simple examples that I don't
> understand enough how to adapt for my own purposes.
> Any help would be appreciated,