繁体   English   中英

C++ lower_bound() 搜索最接近目标值的元素

[英]C++ lower_bound() to search for the closest element to a target value

假设我有一个vector ,其元素是int类型。 如何优雅地使用std::lower_bound()来寻找最接近目标值的元素?

我写了如下所示的代码:

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec {3,4,5,10};
    int target = 6;

    auto found {
        lower_bound(
            vec.begin(),
            vec.end(),
            target,
            [=] (int ele1, int ele2) {
                return (abs(ele1 - target) > abs(ele2 - target));
            }
        )
    };

    cout << (found-vec.begin()) << endl;

    return 0;
}

它返回索引4 ,这意味着found = vec.end() 相反,我想获得2的索引。 我哪里搞砸了?

您在lower_bound中使用的谓词与用于排序vec的谓词不同。 所以你的代码片段有未定义的行为。

您仍然可以使用lower_bound来简单地查找target

auto attempt = lower_bound(vec.begin(), vec.end(), target);

现在,您实际查找的迭代器将是返回的迭代器,或者是指向下一个元素的迭代器:

auto found = attempt == vec.end() ? 
             vec.end() - 1 :   // last element is closest
             attempt == vec.begin() ? 
             vec.begin() :  // first element is closest
             abs(*attempt - target) < abs(*(attempt - 1) - target) ? 
             // somewhere in the middle, then the previous element could be closer
             attempt : attempt - 1;   

这假设vec是非空的,因此您可能还需要进行该检查。

这是一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM