【问题标题】:Binary Search C++ STL二进制搜索 C++ STL
【发布时间】:2010-11-26 09:33:36
【问题描述】:

我有一个 unordered_map 向量,它是根据我定义的比较器函数排序的。我也想使用二进制搜索来查找使用比较器函数的值之一。但是,二进制搜索只返回 bool,我需要结果的索引/迭代器。我能做什么?

【问题讨论】:

    标签: c++ stl


    【解决方案1】:
    #include <algorithm>
    using namespace std;
    
    //!!!!!   a must be sorted using cmp. Question indicates that it is.        
    it = lower_bound(a.begin, a.end(), value, cmp);
    
    //Check that we have actually found the value. 
    //If the requested value is missing
    //then we will have the value before where the requested value 
    //would be inserted.
    if(it == a.end() || !cmp(*it, value))
    {
       //element not found
    } 
    else
    {
       //element found
    }
    

    【讨论】:

    • lower_bound 似乎比简单的“任何匹配值”要慢得多。假设 { 1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,6,7}。中间是 5 - 寻求价值。但是 lower_bound 会向左走。这是不理想的。我可以假设找到左边界的 O(Log(N)) 解决方案。但它是多余的。我对此感到非常沮丧。但是有一个 C 函数 ::bsearch。
    • 如果it!=a.end()!cmp(*it, value) 始终为真。你应该颠倒这些论点。
    【解决方案2】:
    #include <algorithm>
    using namespace std;
    
    it = lower_bound(a.begin, a.end(), value, cmp);
    

    【讨论】:

    • -1 lower_bound 不一定会返回元素。如果元素丢失,它将在它在向量中之前返回元素。
    • 使用 lower_bound 仍然是明智的。使用迭代器,检查它是否可取消引用。如果是,取消引用它并检查搜索到的元素。如果它是元素,你有它,否则它不在那里。
    猜你喜欢
    • 2011-08-15
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2021-09-18
    相关资源
    最近更新 更多