c++的sort函数怎么使用

avatar
作者
筋斗云
阅读量:2

C++的sort函数用于对容器中的元素进行排序。使用sort函数需要包含头文件,并且容器中的元素要支持比较操作。

下面是sort函数的基本用法:

#include <algorithm> #include <vector>  int main() {     std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};      // 对vec中的元素进行升序排序     std::sort(vec.begin(), vec.end());      // 输出排序后的结果     for (int num : vec) {         std::cout << num << " ";     }      return 0; } 

在上面的例子中,我们使用sort函数对vector容器中的元素进行升序排序。sort函数接受两个参数,第一个参数是要排序的元素范围的起始位置,第二个参数是要排序的元素范围的结束位置。

如果要对自定义类型的元素进行排序,需要提供一个比较函数,可以通过lambda表达式或者重载比较运算符来实现。比如对于自定义的Student结构体来说,可以这样使用sort函数:

#include <algorithm> #include <vector>  struct Student {     std::string name;     int score; };  int main() {     std::vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 78}};      // 对students中的元素按照score进行升序排序     std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {         return a.score < b.score;     });      // 输出排序后的结果     for (const Student& student : students) {         std::cout << student.name << " " << student.score << std::endl;     }      return 0; } 

在上面的例子中,我们使用lambda表达式来定义比较函数,对Student结构体中的score进行升序排序。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!