Search code examples
c++binary-search

C++ binary search for a class


I have a class and I want to implement binary_search (from library) to it:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class T_value{
public:

    T_value(const int _timestamp, const string _value) :
        timestamp(_timestamp),
        value(_value)
    {}
    int get_time() {return timestamp;}


private:
    int timestamp;
    string value;
};

int main()
{

    T_value one(1, "one"),
    two(3, "two"),
    three(43, "three"),
    four(-1, "four");
    vector<T_value> v{one,two,three, four};

    cout << binary_search(begin(v), end(v), 3);
}

Is that possible? Should I overload '==' and '<' operators (tried, didn't succeed) or something else?

Thank you in advance!


Solution

  • Since you send an int as the 3rd argument to binary_search, just an operator< will not be enough, because you need to support both int<T_value and T_value<int

    The suggestion is to create a comparator class with the members:

    bool operator()(const T_value& lhs, int rhs) const
    bool operator()(int lhs, const T_value& rhs) const
    

    and send an instance as a fourth parameter.

    Furthermore, the vector should be sorted before binary_search is invoked. You could do this with std::sort, but now you need to support a 3rd type of comparison, a 3rd member of the comparator class could do that, like:

    bool operator()(const T_value& lhs, const T_value& rhs) const
    

    The end result might look something like this