2024年5月11日发(作者:)

c++sort函数降序

§§ 1000

《 c++sort函数降序》

一、 实现思路:

1、 使用 STL 标准库中的数据结构:vector 和 sort 函数,并

且指定排序的比较规则;

2、 定义一个比较函数,使其能够比较出两个参数的大小,并返

回比较后的结果;

3、 使用 vector 给出的数据,调用 sort 函数对其排序,使用

自定义的比较函数设置排序规则;

4、 在比较函数中,如果 x > y,那么就返回真,显示 x > y,

即让 sort 函数按降序排序。

二、 具体代码:

#include

#include

#include

using namespace std;

// 定义比较函数

bool compare (int x, int y) {

§§ 1020

return x > y;

}

- 1 -

int main()

{

// 定义一个 vector 对象,用于保存数据

vector v;

// 给 vector 赋值

_back(10);

_back(30);

_back(20);

_back(50);

_back(40);

// 使用 sort 函数对 vector 进行排序

sort ((), (), compare);

// 输出排序后的结果

for(vector::iterator it = (); it != ();

++it)

cout << *it << ' ';

§§ 1040

cout << endl;

return 0;

}

三、 运行结果:

50 40 30 20 10

- 2 -

四、 总结:

使用 STL 标准库中的 vector 和 sort 函数可以快速实现

c++sort 函数降序,定义自定义的比较函数,并按照 x > y 返回真

的规则,输出排序后的降序结果。

- 3 -