使用声明:
#include<iostream>
#include<algorithm>
using namespace std;
#include <algorithm>
algorithm意为"算法",是C++的标准模版库(STL)中最重要的头文件之一,提供了大量基于迭代器的非成员模版函数。
相关文章可参考:https://blog.csdn.net/ruibin_cao/article/details/83004968(转载)。
#include <iostream>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int b[5] = {6,5,1,8,-1};
sort(b,b + 5);
for(int i = 0;i < 5;i++)
cout << b[i];
return 0;
}
sort(b,b+5);,本句是将b数组的五个数据做从小到大的顺序排序。
部分用法:
int b[5] = {6,5,1,8,-1};
sort(b,b+3);//将数组b中的前三个元素按照从小到大的顺序排列,后面的数据则不动
结果为:1568-1
有类似用法的还有reverse()函数。
#include <iostream>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int b[5] = {6,5,1,8,-1};
sort(b,b + 5);
for(int i = 0;i < 5;i++)
cout << b[i];//-11568
cout << endl;
reverse(b,b + 5);
for(int i = 0;i < 5;i++)
cout << b[i];//8651-1
return 0;
}
1,对int型数组a[n]降序排:
bool cmp (int a, int b)
{
return a > b;
}//降序
2,对string型的数组a[n]排序:
bool cmp (string a, string b)
{
return a > b;
}//降序
3,对结构体型的数组a[n]排序:
bool cmp (node a, node b)
{
return a.x > b.x;
}//降序
ps:如果对结构体进行二级排序,只需在排序函数里面加上if语句。
以上所有的排序函数调用的时候都是用:sort(a, a+n, cmp);
其实强大的stl库给我们提供了辣么多的函数,有一些在这里还是很有用的,比如:
sort(a, a+n, less<数据类型>());//对指定的数据类型升序排
sort(a, a+n, greater<数据类型>());//对指定的数据类型降序排
最后:
虽然这些方法内部的结构我们看不到,但是必要的时候还是需要用到的,因为写原生的C会吃亏坑多,在需要打比赛的时候用这些现成的工具就会快一大截,还不容易出错。
不过C中有很多排序方法,比如桶排序,快速排序,堆之类的算法还是要了解的,毕竟思维很重要。