C++库中用来排序的函数
使用sort()进行排序
- 头文件:algorithm
- 函数原型:
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
- 使用:
sort(首元素地址[必填],尾元素地址的下一个地址[必填],比较函数[非必填])
前两个参数是必填的,如果没有比较函数,默认进行递增排序。
sort还可以对STL容器进行排序,但只能对vector,string和deque使用sort。
- 比较函数
bool cmp(type a1, type a2)
{ return [a1排在a2前面的条件] ; }
举例
- 无比较函数
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int a[6] = {9,4,2,5,6,-1};
sort(a,a+6);
for(int i = 0; i < 6;i++)
{
printtf("%d ",a[i]);
}
return 0;
}
结果:-1 2 4 5 6 9
结果分析:由于没有定义比较函数,所以默认按照递增排序;首元素地址为数组首元素地址,即指向 9,尾元素下一地址为a+6,即指向-1的后一个元素地址。所以对9 ~ -1的这6个元素递增排序。
- 有比较函数
#include <stdio.h>
#include <algorithm>
using namespace std;
bool cmp(int a1,int a2)
{
return a1 > a2;
}
int main()
{
int a[6] = {9,4,2,5,6,-1};
sort(a,a+6,cmp);
for(int i = 0; i < 6;i++)
{
printtf("%d ",a[i]);
}
return 0;
}
结果:9 6 5 4 2 -1
结果分析:与上一个例子不同的是增加了比较函数。观察比较函数,a1排在a2之前的条件是a1>a2,换句话说sort函数按照递减排序。所以得到如上结果。
- 对结构体数组进行排序
#include <stdio.h>
#include <algorithm>
using namespace std;
struct s{
int x,y;
}ss[10];
bool cmp(s a1,s a2)
{
if(a1.x != a2.x)
return a1.x > a2.x;
else
return a1.y < a2.y;
}
int main()
{
ss[0].x = 9; ss[0].y = 1;
ss[1].x = 4; ss[1].y = 2;
ss[2].x = 2; ss[2].y = 3;
ss[3].x = 5; ss[3].y = 4;
ss[4].x = 6; ss[4].y = 5;
ss[5].x = -1; ss[5].y = 6;
ss[6].x = -1; ss[5].y = 5;
ss[7].x = 5; ss[5].y = 5;
ss[8].x = 4; ss[5].y = -1;
ss[9].x = 9; ss[5].y = 3;
sort(ss,ss+10,cmp);
for(int i = 0; i < 6;i++)
{
printf("%d %d\n",ss[i].x ,ss[i].y);
}
return 0;
}
结果:
9 1
9 3
6 5
5 4
5 5
4 -1
4 2
2 3
-1 5
-1 6
结果分析:在这个例子中定义了一个结构体数组ss。观察cmp函数,当a1.x != a2.x时,按x的降序排序;当 a1.x == a2.x时,按y的升序排序。
- 容器的排序
#include <stdio.h>
#include <vector> /*包含vector和string库*/
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v;
v.push_back(3);
v.push_back(2);
v.push_back(1);
sort(v.begin(),v.end());
for(int i = 0; i < 3;i++)
{ printf("%d ",v[i]); }
printf("\n");
string s[3] = {bb, ccc,aaaa};
sort(s,s+3);
for(int i = 0;i < 3;i++)
{ printf("%s\n", s[i]); }
return 0;
}
结果:
1 2 3
aaaa
bb
ccc
结果分析:对于vector,按照int从小到大排序;对于string,按照字典序从小到大排序。