C++ 来自特定位置的上限函数,而不是数据。begin()
我试图从排序对向量中找出大于给定C++ 来自特定位置的上限函数,而不是数据。begin(),c++,search,c++11,stl,C++,Search,C++11,Stl,我试图从排序对向量中找出大于给定数的第一个数。我使用了上限,效果很好。代码如下所示: bool cmp(int n, pair<int, int> const& p) { return (p.first > n) ; } vector<pair<int,int>> v; vector<pair<int,int>>::iterator up; //int Number = ...; // ....... u
数的第一个数。我使用了上限
,效果很好。代码如下所示:
bool cmp(int n, pair<int, int> const& p)
{
return (p.first > n) ;
}
vector<pair<int,int>> v;
vector<pair<int,int>>::iterator up;
//int Number = ...;
// .......
up = upper_bound(v.begin(), v.end(), Number, cmp);
其中,i
表示我要从向量v
的第i个
位置搜索到末尾。但是,它给了我一个错误:
error: no matching function for call to 'upper_bound(__gnu_cxx::__alloc_traits<std::
allocator<std::pair<int, int> > >::
value_type&, std::vector<std::pair<int, int> >::iterator, int&,
bool (&)(int, const std::pair<int, int>&))'
错误:对“上限(\uu gnu\u cxx::\uu alloc\u traits:”的调用没有匹配的函数:
值类型&,标准::向量::迭代器,整数&,
bool(&)(int,const std::pair&)'
造成这种错误的原因是什么?有没有更好的方法从给定位置进行搜索?std::vector::at
不返回迭代器,这是上界所需的迭代器。您可以将迭代器获取到所需位置,并按如下方式传递它:
up = upper_bound(v.begin() + i, v.end(), Number, cmp);
或
std::vector::at
不返回迭代器,这是上限所需的迭代器。您可以将迭代器获取到所需位置,并按如下方式传递它:
up = upper_bound(v.begin() + i, v.end(), Number, cmp);
或
up = upper_bound(std::next(v.begin(), i), v.end(), Number, cmp);