-3
#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<_Compare>::operator()(_Iterator, _Value&) [with _Iterator = arr*; _Value = 常量 int; _Compare = bool ( )(arr&, arr&)]': /usr/include/c++/4.9/bits/stl_algobase.h:965:30:
来自'_ForwardIterator std::__lower_bound(_ForwardIterator, _ForwardIterator, const _Tp&, _Compare) [与 _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, _FIter, const _Tp&, _Compare) [with _FIter = arr*; _Tp = int; _比较=布尔()(arr&, arr&)]' prog.cpp:28:38: 需要从这里 /usr/include/c++/4.9/bits/predefined_ops.h:141:37: 错误: 对类型 'arr&' 的引用的初始化无效'const int' 类型的表达式 { return bool(_M_comp( __it, __val)); } ^

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

运行该函数需要进行哪些更改。

4

2 回答 2

0

正如前面的答案所指出的,lower_bound返回一个迭代器。in
的类型不清楚,也应该和container和compare函数中的类型同类型。 在这种情况下, 的类型应该是。xlower_boundx
xarr

于 2020-07-23T05:40:49.980 回答
0

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

另请注意,索引通常作为 std::size_t 返回,而不是您似乎假设的 int。

于 2017-05-29T16:31:39.360 回答