在C ++中的Structure上使用lower_bound或upper_bound

时间:2017-05-29 15:16:36

标签: c++ struct lower-bound

#include <iostream>
#include <algorithm>

using namespace std;

struct arr
{
int a;int b;
}a[1000];

bool comp(arr &lhs, arr &rhs)
{  return lhs.a < rhs.a ; }

int main() 
{
    int n,i  ;

    sort(a,a+n,comp);

    int ind= lower_bound(a,a+n,x,comp)-a;

    return 0;
}

错误讯息: /usr/include/c++/4.9/bits/predefined_ops.h:实例化'bool __gnu_cxx :: __ ops :: _ Iter_comp_val&lt; _Compare&gt; :: operator()(_ Iterator,_Value&amp;)[with _Iterator = arr *; _Value = const int; _Compare = bool()(arr&amp;,arr&amp;)]': /usr/include/c++/4.9/bits/stl_algobase.h:965:30:需要'_ForwardIterator std :: __ lower_bound(_ForwardIterator,_ForwardIterator,const _Tp&amp;,_Compare)[with _ForwardIterator = arr ; _Tp = int; _Compare = __gnu_cxx :: __ ops :: _ Iter_comp_val]' /usr/include/c++/4.9/bits/stl_algo.h:2036:46:需要'_FIter std :: lower_bound(_FIter,_Fter,const _Tp&amp;,_Compare)[with _FIter = arr *; _Tp = int; _Compare = bool()(arr&amp;,arr&amp;)]' prog.cpp:28:38:从这里要求 /usr/include/c++/4.9/bits/predefined_ops.h:141:37:错误:'arr&amp;'类型引用的初始化无效来自'const int'类型的表达式   {return bool(_M_comp( __ it,__ value)); }                                      ^

我希望在struct上使用lower_bound来搜索等于a [i] .a的值x?我已相应地构建了比较器函数,但得到了一条很长的错误消息,我无法做任何事情。

运行该功能需要进行哪些更改。

2 个答案:

答案 0 :(得分:0)

lower_bound返回迭代器,而不是找到的元素的索引。您需要使用std :: distance来检索索引,但通常情况下,迭代器是您需要/想要进一步处理的内容。

另请注意,索引通常以std :: size_t的形式返回,而不是您认为的int。

答案 1 :(得分:0)

如先前答案中所述,lower_bound返回一个迭代器。
xlower_bound的类型不清楚,x也应该与容器和比较函数中的类型相同。
在这种情况下,x的类型应为arr