gpt4 book ai didi

c++ - 二进制搜索 C++ STL

转载 作者:IT老高 更新时间:2023-10-28 22:00:47 26 4
gpt4 key购买 nike

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

最佳答案

#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
}

关于c++ - 二进制搜索 C++ STL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4284049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com