当用sort()想对结构体进行排序的时候,这时候就需要自己写一个排序函数了
写这个是因为自己好久没用STL里面的sort()函数了。都忘记了 。再次实现一下
其实排序函数也很简单,自己实现
代码如下:
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
typedef struct index
{
int a,b;
}index;
bool cmp(index a , index b)
{
if (a.a > b.a )
{
return true;
}
else
if ( a.a == b.a )
{
if (a.b > b.b )
{
return true ;
}
}
return false ;
}
int main()
{
index c[100];
srand( time(0) );
for (int i = 0 ; i < 100 ; ++i )
{
c[i].a = rand()%10 ;
c[i].b = rand()%10 ;
}
sort( c , c+100 , cmp );
for (i = 0 ; i < 100 ; ++i )
{
cout<<c[i].a <<" "<<c[i].b <<endl;
}
return 0;
}
排序顺序:
首先按照a递减的方式排序。
若a相同,则按照b的递减方式排序