【问题标题】:syntax: doing binary_search (STL) for sorted vector of pointers to struct语法:对结构指针的排序向量执行 binary_search (STL)
【发布时间】:2015-06-07 16:54:45
【问题描述】:

对不起,如果这是一个愚蠢的问题,但即使在阅读了一堆文档和论坛帖子之后,我似乎还是无法编译:

基本上,我有这个结构:

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

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

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

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 排序非常相似,并尝试这样调用它:

    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 正常工作?

【问题讨论】:

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


    【解决方案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 表达式作为比较函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2020-03-15
      • 1970-01-01
      • 2012-02-07
      • 2014-12-29
      • 1970-01-01
      相关资源
      最近更新 更多