2024年3月13日发(作者:)
c++的list的sort方法
C++中的list容器提供了sort()方法来对元素进行排序。sort()
方法可以接收一个可选的比较函数参数,用于指定排序的规则。如果
未提供比较函数,则默认按照元素的小于关系进行排序。在使用sort()
方法时,需要包含
list容器进行排序的示例代码:
```cpp
#include
#include
#include
using namespace std;
int main() {
list
// 使用默认的小于关系进行排序
();
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条)