c++ sort用法

c++ sort用法


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

c++ sort用法

在C++中,你可以使用sort函数对一个数组或容器进行排序。

sort函数属于头文件中的一个函数,它提供了多个

重载版本,可以满足不同的排序需求。

以下是sort函数的常见用法:

1. 对数组排序:

```cpp

#include

int arr[] = {5, 2, 9, 1, 3};

std::sort(arr, arr + sizeof(arr) / sizeof(arr[0]));

// 输出排序后的数组

for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {

std::cout << arr[i] << " ";

}

```

2. 对容器排序:

```cpp

#include

#include

std::vector vec = {5, 2, 9, 1, 3};

std::sort((), ());

// 输出排序后的容器

for(int i = 0; i < (); i++) {

std::cout << vec[i] << " ";

}

```

3. 自定义排序规则:

```cpp

#include

#include

struct Person {

std::string name;

int age;

};

// 自定义排序规则:根据年龄升序排序

bool ageComparison(const Person& p1, const Person& p2) {

return < ;

}

int main() {

std::vector people = {{"Amy", 25}, {"Tom", 20},

{"John", 30}};

std::sort((), (), ageComparison);

// 输出排序后的人员信息

for(int i = 0; i < (); i++) {

std::cout << people[i].name << " (" << people[i].age << ")"

<< std::endl;

}

}

```

在以上的示例中,sort函数对给定的数组或容器进行了排序。

对于数组,我们可以使用`std::sort(arr, arr + sizeof(arr) /

sizeof(arr[0]))`来指定要排序的范围。对于容器,我们可以使用

`std::sort((), ())`来指定要排序的范围。

如果需要自定义排序规则,可以提供一个函数或函数对象来作

为sort函数的第三个参数。该函数或函数对象用于比较数组或

容器中的元素,返回一个布尔值来决定元素顺序。在上述示例

中,我们提供了一个自定义的比较函数`ageComparison`来按照

人员的年龄升序排序。


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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信