compare function for upper_bound / lower_bound

You can further improve Mark's solution by creating a static instance of MyClassLessThan in MyClass

class CMyClass 
{
   static struct _CompareFloatField
   {
      bool operator() (const MyClass & left, float right) //...
      // ...
   } CompareFloatField;
};

This way you can call lower_bound in the following way:

std::lower_bound(coll.begin(), coll.end(), target, CMyClass::CompareFloatField);

This makes it a bit more readable


What function did you pass to the sort algorithm? You should be able to use the same one for upper_bound and lower_bound.

The easiest way to make the comparison work is to create a dummy object with the key field set to your search value. Then the comparison will always be between like objects.

Edit: If for some reason you can't obtain a dummy object with the proper comparison value, then you can create a comparison functor. The functor can provide three overloads for operator() :

struct MyClassLessThan
{
    bool operator() (const MyClass & left, const MyClass & right)
    {
        return left.key < right.key;
    }
    bool operator() (const MyClass & left, float right)
    {
        return left.key < right;
    }
    bool operator() (float left, const MyClass & right)
    {
        return left < right.key;
    }
};

As you can see, that's the long way to go about it.

Tags:

Algorithm

C++

Stl