Custom Comparator for std::binary_search

I'm trying to use the STL's binary search in <algorithm> but unlike other functions that take a comparator, binary_search won't work with my custom comparator.

For example, in std::sort(vec.begin(), vec.end(), MYFUNCTION) MYFUNCTION needs to return a boolean.

However, in binary_search, MYFUNCTION also needs to return a boolean. How would I do this with custom objects? My custom comparator returns an int, as I modeled by obj1.compare(const Obj& obj2) function after the str.compare() function, (which also returns an int instead of a bool). Would I have to overload my operators?
Last edited on
You should be able to use the same comparison function for both std::sort and std::binary_search.

std::sort and std::binary_search uses the < operator by default. For std::string str1 < str2 gives the same value as
str1.compare(str2) < 0 so if your compare function works the same way I guess that is what you should probably do in the comparison function that you pass to std::sort and std::binary_search.
Last edited on
You can even wrap your compare easily with a lambda:
1
2
3
std::sort( vec.begin(), vec.end(),
           [](const Obj& lhs, const Obj& rhs){ return lhs.compare(rhs) < 0; }
         );
Topic archived. No new replies allowed.