Reputation: 165
I want to overload operator < between 2 pair. It works when i compare using < but it doesn't work when i use sort function built_in cpp. #include using namespace std;
typedef pair<int,int> pii;
bool operator < (const pii &a,const pii &b){
return a.second<b.second;
}
int main()
{
pii a,b;
a=make_pair(1,4);
b=make_pair(2,3);
if(a<b) cout<<"a<b\n";
else cout<<"b<a\n";
vector<pii> v;
v.push_back(a);
v.push_back(b);
sort(v.begin(),v.end());
for(auto x:v)
cerr<<x.first<<" "<<x.second<<endl;
return 0;
}
Output:
b<a
1 4
2 3
I 'm confused why it doesn't print:
b<a
2 3
1 4
Upvotes: 3
Views: 92
Reputation: 12928
std::pair
already has a built in operator<
. If you want to sort by a different criteria you can pass a comparison function.
std::sort(v.begin(),v.end(), [](auto& lhs, auto& rhs){ return lhs.second < rhs.second; });
Upvotes: 7