# Thread: how to sort ?

1. ## how to sort ?

Assume there are two arrays

arr1[] arr2[]
1 0
2 5
2 0
2 10
4 9
4 9
5 0

i need to sort arr1[] in such a way the resultant array is

5 4(9) 4(9) 2(10) 2(5) 2(0) 1 // preference is given to number in arr1 if equal the arr2 is consulted

is there any way to do this using STL in C++ ??

plz help !
thank u ! 2. Given that the C++ STL has something called "sort" it's possible. However, you would have to tie the two numbers together into one object. Otherwise you'll have to roll your own sorting function (not that that's exceptionally difficult). 3. ## re :

This doesnot work !

Code:
```#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector< pair<int,int> >arr(101);
int main()
{
int i,a,b,c,n;

cin>>n;
arr.clear();
for(i=0;i<n;i++)
{
cin>>a>>b;
arr[i].first=a;
arr[i].second=b;
}
sort(arr.begin(),arr.end());

for(i=0;i<n;i++)
cout<<arr[i].first<<" "<<arr[i].second<<endl;
return 0;
}``` 4. You're sorting the entire array, but only accepting n inputs.

Also, if the < operator for std::​pair doesn't do what you want (or, if it isn't even defined, which I suspect may be the case), then you'll need to supply a predicate to std::sort. (A predicate is a class with bool operator () (item_a, item_b) defined) 5. The operator < for pairs is in the <utility> header (I had to look that up). And if n does not equal 101 then it's not going to work anyway -- you should use arr[n] instead of arr.end() in your sort. 6. [
Code:
```#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;

vector< pair<int,int> >arr;
int main()
{
int i,a,b,c,n;

cin>>n;
arr.clear();
for(i=0;i<n;i++)
{
cin>>a>>b;
arr.push_back(make_pair(-a,-b));
}
sort(arr.begin(),arr.end());

for(i=0;i<n;i++)
cout<<-arr[i].first<<" "<<-arr[i].second<<endl;
return 0;
}```
Pair has a built-in sort, to reverse the order just negate it (and back again for output). 7. ## Thanks

Might seem a bit foolish to thank after a long time..but still !!

Thanks 0rion Popular pages Recent additions 