Вопрос

I am trying to find out from a sorted pair vector the first number greater than a given Number. I used upper_bound and it works well. The code is shown below:

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

Now I want to search from a specific position instead of the beginning. So I changed the code into:

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

where i means that I want to search from the ith position of the vector v to end. However, it gives me an error:

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

What's the reason that caused such an error? And is there any better method to search from a given position?

Это было полезно?

Решение

std::vector::at does not return an iterator, which is what you need for upper_bound. You can obtain an iterator to the required position and pass it like this:

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

or

up = upper_bound(std::next(v.begin(), i), v.end(), Number, cmp);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top