从特定位置调用Upper_bound函数,而不是使用data.begin()

upper_bound function from a specific position instead of data.begin()

本文关键字:data begin 位置 定位 调用 Upper 函数 bound      更新时间:2023-10-16

我试图从排序对向量中找出第一个大于给定Number的数字。我用upper_bound,它工作得很好。代码如下所示:

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);

现在我想从一个特定的位置而不是开始搜索。所以我把代码改成:

up = upper_bound(v.at(i), v.end(), Number, cmp);

,其中i表示我想从向量vith位置搜索到end。然而,它给了我一个错误:

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>&))'

是什么原因导致了这样的错误?有没有更好的从给定位置搜索的方法?

std::vector::at不返回迭代器,这是upper_bound所需要的。您可以获取到所需位置的迭代器,并像这样传递它:

up = upper_bound(v.begin() + i, v.end(), Number, cmp);

up = upper_bound(std::next(v.begin(), i), v.end(), Number, cmp);