C++:Sort()排序函数的使用

版权声明:请尊重原创成果,未经允许,禁止转载 https://blog.csdn.net/qq_31441951/article/details/87392526
  • Sort(begin,end)//排序函数,从begin到end
#include<algorithm>  //sort函数引用的头文件
#include<iostream>
#include<functional> //用法3:排序标准库直接调用的头文件
using namespace std;

//用法2:自己编写比较函数
bool comp(int a, int b)
{
	return a > b;//降序算法
}


int main(void)
{
	int i;
	int a[5] = { 4, 3, 88, 19, 32 };
	for (i = 0; i < 5; i++)
		cout << a[i] << "  ";
	cout << endl;
	sort(a, a + 5);		//用法1:默认是升序算法
	cout << "sort 默认排序:" ;
	for (i = 0; i < 5; i++)
		cout << a[i] << "  ";

	cout << endl << "sort-comp降序:";
	sort(a, a + 5, comp);
	for (i = 0; i < 5; i++)
		cout << a[i] << "  ";

	//用法3:排序标准库直接调用使用  
	//标准排序函数有:equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>
	cout << endl << "sort-标准库:";
	sort(a, a + 5, greater<int>());
	for (i = 0; i < 5; i++)
		cout << a[i] << "  ";

	while (1);
	return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_31441951/article/details/87392526