Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upper_bound on vector<pair<int,int>> [closed]

Tags:

c++

stl

I'm trying to use upper_bound on a vector<pair<int,int>>, like this :

vector<pair<int,int>> data;
auto up = upper_bound(data.begin(), data.end(), 0);

VS2012 gives me the following error :

error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const int'

why is it trying to compare a const int with a pair<int,int> ?

I tried writing my own comparison function, but it doesn't change anything. The compiler tries to convert a pair<int,int> into a const int if I do that.

like image 451
Simon-Okp Avatar asked Feb 17 '13 14:02

Simon-Okp


2 Answers

You are comparing a pair with a number, there is no predefined comparison operator for that. You might want to change it into something like this:

auto up = upper_bound(data.begin(), data.end(), make_pair(0, 0));

Alternatively, if there is a specific logic in your application for comparing a pair with a single number, you can provide your own comparison function:

bool cmp(int n, pair<int, int> const& p)
{
    // For instance...
    return ((p.first < n) && (p.second < n));
}

int main()
{
    vector<pair<int,int>> data;
    auto up = upper_bound(data.begin(), data.end(), 0, cmp);
}
like image 92
Andy Prowl Avatar answered Sep 23 '22 19:09

Andy Prowl


why is it trying to compare a const int with a pair ?

Because you told it to. Your comparison value is 0, but your element type is pair<int,int>.

Duh doy!

Perhaps you're looking for:

auto up = upper_bound(data.begin(), data.end(), make_pair(0, 0));
like image 25
Lightness Races in Orbit Avatar answered Sep 25 '22 19:09

Lightness Races in Orbit