syntax: doing binary_search (STL) for sorted vector of pointers to struct

647 views Asked by At

sorry if this is a noobish question but even after reading a bunch of documentation and forum posts I just can't seem to get this to compile:

Basically, I've got this struct:

struct Entry{
    unsigned long long time;
    // other things...
};

And I've successfully created a vector<Entry*> timestampSearch.

timestampSearch has been sorted, and I'm pretty sure successfully, based on the member variable unsigned long long time in each of the objects of type Entry that each of the elements of timestampSearch point to.

FWIW, it was sorted via <algorithm>'s std::sort function, using this predicate:

// time compare predicate/functor to sort by timestamp   
struct cmp_time_cat_entryID{
    inline bool operator() (Entry* entry1, Entry* entry2) const{
        if (entry1->time == entry2->time){
            if (entry1->category_lower == entry2->category_lower){
                return (entry1->entryID < entry2->entryID);
            }
            else{
                return (entry1->category_lower < entry2->category_lower);
            }
        }
        return (entry1->time < entry2->time);
    }
};

...and called like this:

sort(timestampSearch.begin(), timestampSearch.end(), cmp_time_cat_entryID());

So, when it came time to binary_search timestampSearch, I had figured the syntax for calling STL binary_search would be very similar to STL sort, and tried to call it like so:

    bool time1present = false;
    unsigned long long time1 = 0425215422

    time1present = binary_search(timestampSearch.begin(),
                                   timestampSearch.end(),
                                   time1, 
                                   cmp_time());

...with a very similar predicate that might (?) save on a few cycles:

struct cmp_time{
    inline bool operator() (Entry* entry1, Entry* entry2) const{
        return (entry1->time == entry2->time);
    }
};

However, I'm getting this compile error:

    Error   1   error C2664: 
'bool cmp_time::operator ()(Entry *,Entry *) const' : 
cannot convert argument 1 from 'const unsigned __int64' to 'Entry *'

c:\program files (x86)\microsoft visual studio 12.0\vc\include\algorithm    2666    1   test_unordered_map

Can anyone help me fix this and get binary_search working?

1

There are 1 answers

0
a_pradhan On

Your binary search comparison function compares between Entry object whereas you are passing an unsigned long long type (which cannot be converted to Entry*).

Create a new instance of Entry object (which is to be searched) and pass it to the binary_search function or create the appropriate comparison function.

bool operator()(unsigned long long time, const Entry* ob)
{
    return time == ob->time ;
}

In C++11 and above, you can also use a lambda expression as the comparison function.