Reputation: 73
How to sort a 2d array according to the second column using stl sort function ?
For eg
If we have an array a[5][2] and we want to to sort according to the ar[i][1] entry , how do we do it using the stl sort function. I understand we have to use a boolean function to pass as the third parameter but I am not able to design the appropriate boolean function ?
Upvotes: 1
Views: 8486
Reputation: 647
The stl sort requires the rvalue of the iterator being passed as the arguments. If you wanna use the sort function, you will have to compile in c++11 and use the array stl to store the array. The code is as follows
#include "bits/stdc++.h"
using namespace std;
bool compare( array<int,2> a, array<int,2> b)
{
return a[0]<b[0];
}
int main()
{
int i,j;
array<array<int,2>, 5> ar1;
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
cin>>ar1[i][j];
}
}
cout<<"\n earlier it is \n";
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
cout<<ar1[i][j]<<" ";
}
cout<<"\n";
}
sort(ar1.begin(),ar1.end(),compare);
cout<<"\n after sorting \n";
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
cout<<ar1[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
Compiling in c++11 can be done by g++ -std=c++11 filename.cpp -o out. In case you do not want to use c++11 or use the "array" stl, use the std::qsort function. With this you can use the traditional way to define the arrays like int a[10][2]. The code is as follows
#include "bits/stdc++.h"
using namespace std;
int compare( const void *aa, const void *bb)
{
int *a=(int *)aa;
int *b=(int *)bb;
if (a[0]<b[0])
return -1;
else if (a[0]==b[0])
return 0;
else
return 1;
}
int main()
{
int a[5][2];
cout<<"enter\n";
for(int i=0;i<5;i++)
{
for(int j=0;j<2;j++)
{
cin>>a[i][j];
}
//cout<<"\n";
}
cout<<"\n\n";
qsort(a,5,sizeof(a[0]),compare);
for(int i=0;i<5;i++)
{
for(int j=0;j<2;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
Upvotes: 3
Reputation: 2250
Make your own compare function.
See the Beginners guide to std::sort(). http://www.cplusplus.com/articles/NhA0RXSz/
Upvotes: 0