【发布时间】:2010-11-26 09:33:36
【问题描述】:
我有一个 unordered_map 向量,它是根据我定义的比较器函数排序的。我也想使用二进制搜索来查找使用比较器函数的值之一。但是,二进制搜索只返回 bool,我需要结果的索引/迭代器。我能做什么?
【问题讨论】:
我有一个 unordered_map 向量,它是根据我定义的比较器函数排序的。我也想使用二进制搜索来查找使用比较器函数的值之一。但是,二进制搜索只返回 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
}
【讨论】:
it!=a.end(),!cmp(*it, value) 始终为真。你应该颠倒这些论点。
#include <algorithm>
using namespace std;
it = lower_bound(a.begin, a.end(), value, cmp);
【讨论】: