二叉搜索C ++ STL [英] Binary Search C++ STL
本文介绍了二叉搜索C ++ STL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个unordered_map的向量,它是基于我定义的比较器函数排序的。我想使用二进制搜索来寻找一个值使用比较器函数,以及。但是,二叉搜索只返回bool,我需要结果的索引/迭代器。我可以做什么?
I have a vector of unordered_map which is sorted based on the comparer function I defined. I would like to use binary search to look for one of the value using the comparer function as well. However, binary search only return bool and I need the index / iterator of the result. What could I do?
推荐答案
#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 ++ STL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文