compare function for upper_bound / lower_bound

前端 未结 4 473
粉色の甜心
粉色の甜心 2020-12-10 03:04

I want to find the first item in a sorted vector that has a field less than some value x.
I need to supply a compare function that compares \'x\' with the internal value

4条回答
  •  萌比男神i
    2020-12-10 03:53

    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.

提交回复
热议问题