Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 二进制搜索C++;STL_C++_Stl - Fatal编程技术网

C++ 二进制搜索C++;STL

C++ 二进制搜索C++;STL,c++,stl,C++,Stl,我有一个无序_映射向量,它是根据我定义的比较器函数排序的。我想使用二进制搜索来寻找一个值,同时使用比较器函数。然而,二进制搜索只返回bool,我需要结果的索引/迭代器。我能做什么?#包括 #include <algorithm> using namespace std; it = lower_bound(a.begin, a.end(), value, cmp); 使用名称空间std; it=下限(a.begin,a.end(),value,cmp); #包括 使用名称空间std

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

#包括
#include <algorithm>
using namespace std;

it = lower_bound(a.begin, a.end(), value, cmp);
使用名称空间std; it=下限(a.begin,a.end(),value,cmp);
#包括
使用名称空间std;
//!!!!!   a必须使用cmp进行排序。问题表明它是。
it=下限(a.begin,a.end(),value,cmp);
//检查我们是否实际找到了值。
//如果缺少请求的值
//然后我们将在请求的值之前有一个值
//将插入。
if(it==a.end()| |!cmp(*it,value))
{
//未找到元素
} 
其他的
{
//元素发现
}

-1下限不一定返回元素。如果元素丢失,它将在向量中返回元素之前返回元素。使用下限仍然是明智的。以迭代器为例,检查它是否可取消引用。如果是,则取消引用它并检查搜索的元素。如果它是元素,您就拥有它,否则它就不在其中。下限似乎比简单的“任何匹配值”慢得多。假设{1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7}。中间是5-a的追求值。但下界将向左移动。这是不合时宜的。我可以假设求左边界的O(Log(N))解。但这是多余的。我对此感到非常不安。但是有一个C函数::b搜索。
!cmp(*it,value)
如果
it=a、 end()
。你应该把论点颠倒过来。
#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
}