繁体   English   中英

在 C++ 中对 Structure 使用 lower_bound 或 upper_bound

[英]using lower_bound or upper_bound on Structure in C++

#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 = const 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) [with _ForwardIterator = arr ; _Tp = 整数; _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) [与_FIter = arr*; _Tp = 整数; _Compare = bool ( )(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 ? 我已经相应地构建了比较器函数,但收到了一条很长的错误消息,我对此无能为力。

函数运行需要哪些更改。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM