【问题标题】:upper_bound function from a specific position instead of data.begin()来自特定位置而不是 data.begin() 的上界函数
【发布时间】:2014-07-02 18:25:48
【问题描述】:

我试图从排序对向量中找出大于给定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表示我要从向量v的ith位置搜索到结束。但是,它给了我一个错误:

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

造成这种错误的原因是什么?有没有更好的方法从给定位置进行搜索?

【问题讨论】:

    标签: c++ search c++11 stl


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 2012-05-20
      相关资源
      最近更新 更多