首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >二进制搜索C++ STL

二进制搜索C++ STL
EN

Stack Overflow用户
提问于 2010-11-26 17:33:36
回答 2查看 13K关注 0票数 20

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-26 18:00:28

代码语言:javascript
复制
#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
}
票数 23
EN

Stack Overflow用户

发布于 2010-11-26 17:35:32

代码语言:javascript
复制
#include <algorithm>
using namespace std;

it = lower_bound(a.begin, a.end(), value, cmp);
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4284049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档