Reputation: 551
I would like to sort vector by its second element. The code is following:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(const pair<int,int>&i, const pair<int,int>&j){
return i.second < j.second;
}
int main()
{
vector<pair<int,int> >a(100);
// values for test
a[0].first=0; a[0].second=21;
a[1].first=1; a[1].second=100;
a[2].first=2; a[2].second=100;
a[3].first=3; a[3].second=30;
a[4].first=4; a[4].second=17;
sort(a.begin(),a.end(),compare);
for(int i=0;i<5;i++)
cout << a[i].second << " " << a[i].first << endl;
}
The program returns
0 0
0 0
0 0
0 0
0 0
Where I made a mistake?
Upvotes: 0
Views: 1458
Reputation: 5359
Since the rest 95 elements are not assigned, they are by default (0,0)
. So you need to sort the first 5 elements only.
sort(a.begin(),a.begin()+5,compare);
Upvotes: 3
Reputation: 70931
The sorting of a vector<pair<int, int> >
works just the way you use it. However you have another problem. This code - vector<pair<int,int> >a(100);
creates a vector of size 100
and fills it with pairs of (0,0)
. Thus when you sort it the first 5 elements are (0,0)
.
Upvotes: 3
Reputation: 9373
Your vector is of size 100, but you only populated 5 elements. The rest will all be (0, 0), which your compare() correctly puts at the front.
Upvotes: 2