关于sort函数从大到小排序的方法(实用)

关于sort函数从大到小排序的方法(实用)

初始情况:

#include
#include
using namespace std;
int main()
{
	int a[5] = { 5,1,2,4,3 };
	sort(a, a + 5);
	for (int i = 0; i < 5; i++)
		cout << a[i]<<" ";
	return 0;
}

第一种:是使用greater()

#include
#include
using namespace std;
int main()
{
	int a[5] = { 5,1,2,4,3 };
	sort(a, a + 5,greater<int>());
	for (int i = 0; i < 5; i++)
		cout << a[i]<<" ";
	return 0;
}

第二种:自己创建一个比较函数,

#include
#include
using namespace std;
int yang(int a, int b);
int main()
{
	int a[5] = { 5,1,2,4,3 };
	sort(a, a + 5,yang);
	for (int i = 0; i < 5; i++)
		cout << a[i]<<" ";
	return 0;
}
int yang(int a, int b)
{
	return a > b;

}

将两种方法汇到一起:

#include
#include
using namespace std;
int yang(int a, int b);
int main()
{
	int a[5] = { 5,1,2,4,3 };
	int b[5] = { 5,1,2,4,3 };
	sort(b, b + 5,greater<int>());
	sort(a, a + 5,yang);
	for (int i = 0; i < 5; i++)//输出自己创建比较函数的值
		cout << a[i]<<" ";
	    cout <<endl;
	for (int i = 0; i < 5; i++)//输出greater的值
		cout << b[i] << " ";
	return 0;
}
int yang(int a, int b)
{
	return a > b;

}

运行代码结果:
关于sort函数从大到小排序的方法(实用)_第1张图片

你可能感兴趣的:(c\c++有用知识,c++,开发语言)