STL中的sort函数包含于文件”algorithm“中,sort有两个重载函数,因此有两种调用方式:sort(begin, end)和sort(begin, end, compare),默认的排序结果是从小到大。
1. 对于基本数据类型我们可以直接使用第一种调用方式
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int ar[10];
for (int i=0; i<10; ++i)
{
ar[i] = 10 - i;
}
cout<<"原序列:";
for (int i=0; i<10; ++i)
{
cout<<ar[i]<<" ";
}
cout<<endl;
sort(ar, ar+10);
for (int i=0; i<10; ++i)
{
cout<<ar[i]<<" ";
}
return 1;
}
2. 当我们想要的排序结果是从达到小时需要定义比较函数
#include <algorithm>
#include <iostream>
using namespace std;
bool comp(int a, int b)
{
return a>b;
};
int main()
{
int ar[10];
for (int i=0; i<10; ++i)
{
ar[i] = i;
}
cout<<"原序列:";
for (int i=0; i<10; ++i)
{
cout<<ar[i]<<" ";
}
cout<<endl;
sort(ar, ar+10, comp);
for (int i=0; i<10; ++i)
{
cout<<ar[i]<<" ";
}
return 1;
}
3. 对于复杂的数据结构我们有两种处理策略
3.1 类似2中所示定义比较函数
例子略
3.2 在数据结构中定义比较函数
#include <algorithm>
#include <iostream>
using namespace std;
struct node
{
int a;
int b;
bool operator<(struct node n1)
{
return b < n1.b;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
struct node *no = new struct node[10];
for (int i=0; i<10; ++i)
{
no[i].a = i;
no[i].b = 10 - i;
}
for (int i=0; i<10; ++i)
{
cout<<no[i].a<<" "<<no[i].b<<endl;
}
cout<<"///"<<endl;
sort(no, no+10);
for (int i=0; i<10; ++i)
{
cout<<no[i].a<<" "<<no[i].b<<endl;
}
return 0;
}
同样道理将struct node中的return b < n1.b 改为 return b > n1.b排序结果将是从大到小。