语法:对struct的指针的排序向量执行binary_search(STL)

时间:2015-06-07 16:54:46

标签: c++ pointers vector stl binary-search

抱歉,如果这是一个愚蠢的问题,但即使在阅读了大量文档和论坛帖子后,我似乎无法将其编译:

基本上,我有这个结构:

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

我已成功创建vector<Entry*> timestampSearch

timestampSearch已经排序了,我非常确定成功,基于unsigned long long time类型的每个对象中的成员变量EntrytimestampSearch的每个元素都指向到。

FWIW,它使用此谓词通过<algorithm>的std :: sort函数进行排序:

// 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);
    }
};

......并且这样称呼:

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

所以,当到了binary_search timestampSearch的时候,我认为调用STL binary_search的语法与STL sort非常相似,并试图像这样调用它:

    bool time1present = false;
    unsigned long long time1 = 0425215422

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

...有一个非常相似的谓词可能(?)保存几个周期:

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

但是,我收到了这个编译错误:

    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

任何人都可以帮我修复这个并让binary_search工作吗?

1 个答案:

答案 0 :(得分:1)

您的二进制搜索比较函数会比较Entry个对象,而您传递unsigned long long类型(无法转换为Entry*)。

创建Entry对象的新实例(将被搜索)并将其传递给binary_search函数或创建适当的比较函数。

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

在C ++ 11及更高版本中,您还可以使用lambda表达式作为比较函数。