c++

c++中怎么用sort函数进行排序

小亿
81
2023-10-19 11:40:28
栏目: 编程语言

在C++中,可以使用sort()函数来对数组、向量以及其他容器进行排序。以下是使用sort()函数进行排序的示例:

  1. 对数组进行排序:
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {4, 2, 8, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n);
std::cout << "排序后的数组:";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}

输出:

排序后的数组:1 2 4 5 8
  1. 对向量进行排序:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {4, 2, 8, 5, 1};
std::sort(vec.begin(), vec.end());
std::cout << "排序后的向量:";
for (int i : vec) {
std::cout << i << " ";
}
return 0;
}

输出:

排序后的向量:1 2 4 5 8
  1. 对自定义对象进行排序:
#include <iostream>
#include <vector>
#include <algorithm>
// 定义自定义对象
struct Student {
std::string name;
int age;
double score;
};
// 自定义比较函数,按照分数从小到大排序
bool compare(const Student& s1, const Student& s2) {
return s1.score < s2.score;
}
int main() {
std::vector<Student> students = {
{"Alice", 18, 90.5},
{"Bob", 20, 85.0},
{"Charlie", 19, 92.3}
};
std::sort(students.begin(), students.end(), compare);
std::cout << "排序后的学生信息:" << std::endl;
for (const Student& s : students) {
std::cout << "姓名:" << s.name << ",年龄:" << s.age << ",分数:" << s.score << std::endl;
}
return 0;
}

输出:

排序后的学生信息:
姓名:Bob,年龄:20,分数:85
姓名:Alice,年龄:18,分数:90.5
姓名:Charlie,年龄:19,分数:92.3

以上示例展示了如何使用sort()函数进行排序,可以根据需要自定义比较函数来实现不同的排序方式。

0
看了该问题的人还看了