c++的list的sort方法

c++的list的sort方法


2024年3月13日发(作者:)

c++的list的sort方法

C++中的list容器提供了sort()方法来对元素进行排序。sort()

方法可以接收一个可选的比较函数参数,用于指定排序的规则。如果

未提供比较函数,则默认按照元素的小于关系进行排序。在使用sort()

方法时,需要包含头文件。以下是使用sort()方法对

list容器进行排序的示例代码:

```cpp

#include

#include

#include

using namespace std;

int main() {

list myList = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

// 使用默认的小于关系进行排序

();

for (auto it = (); it != (); ++it)

{

cout << *it << ' ';

}

cout << endl;

// 使用自定义的比较函数进行排序

auto cmp = [](int a, int b) { return a % 3 < b % 3; };

- 1 -

(cmp);

for (auto it = (); it != (); ++it)

{

cout << *it << ' ';

}

cout << endl;

return 0;

}

```

输出结果为:

```

1 1 2 3 3 4 5 5 5 6 9

3 6 9 1 1 4 2 5 5 3 5

```

在第一个sort()方法中,使用了默认的小于关系进行排序,结

果按照从小到大的顺序输出。在第二个sort()方法中,使用了自定

义的比较函数,按照元素对3取余数的大小进行排序,结果按照余数

为0、1、2的顺序输出。

- 2 -


发布者:admin,转转请注明出处:http://www.yc00.com/news/1710310446a1735160.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信