二进制搜索C ++ STL

时间:2010-11-26 09:33:36

标签: c++ stl

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

2 个答案:

答案 0 :(得分:22)

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

答案 1 :(得分:15)

#include <algorithm>
using namespace std;

it = lower_bound(a.begin, a.end(), value, cmp);