FX-std::vector排序
在 C++ 中,std::vector
可以使用标准库中的 std::sort
函数对元素进行排序。std::sort
位于 <algorithm>
头文件中,是一个非常高效的排序算法(通常是快速排序或混合排序)。
以下是 std::sort
的基本用法:
1. 包含头文件
#include <algorithm> // for std::sort
#include <vector>
2. 默认排序(升序)
std::sort
默认使用 <
运算符对元素进行升序排序。
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 默认升序排序
std::sort(vec.begin(), vec.end());
// 输出结果
for (int value : vec) {
std::cout << value << " ";
}
// 输出: 1 2 5 5 6 9
3. 降序排序
可以通过传递一个自定义的比较函数来实现降序排序。C++ 提供了 std::greater
来简化这一操作。
#include <functional> // for std::greater
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 降序排序
std::sort(vec.begin(), vec.end(), std::greater<int>());
// 输出结果
for (int value : vec) {
std::cout << value << " ";
}
// 输出: 9 6 5 5 2 1
4. 自定义排序规则
如果需要根据特定规则排序,可以传递一个自定义的比较函数或 lambda 表达式。
示例 1:按绝对值排序
std::vector<int> vec = {-5, 2, -9, 1, 5, 6};
// 按绝对值升序排序
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return abs(a) < abs(b);
});
// 输出结果
for (int value : vec) {
std::cout << value << " ";
}
// 输出: 1 2 -5 5 6 -9std::vector<int> vec = {-5, 2, -9, 1, 5, 6};
示例 2:按字符串长度排序
std::vector<std::string> vec = {"apple", "banana", "kiwi", "mango"};
// 按字符串长度升序排序
std::sort(vec.begin(), vec.end(), [](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
// 输出结果
for (const std::string& str : vec) {
std::cout << str << " ";
}
// 输出: kiwi mango apple banana
5. 部分排序
如果只需要对部分元素进行排序,可以使用 std::partial_sort
。
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 对前 3 个元素进行排序
std::partial_sort(vec.begin(), vec.begin() + 3, vec.end());
// 输出结果
for (int value : vec) {
std::cout << value << " ";
}
// 输出: 1 2 5 9 5 6
6. 排序自定义对象
如果 std::vector
存储的是自定义对象,可以通过重载 <
运算符或提供自定义比较函数来排序。
示例:按对象的某个成员变量排序
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
// 重载 < 运算符
bool operator<(const Person& other) const {
return age < other.age;
}
};
int main() {
std::vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}};
// 按年龄升序排序
std::sort(people.begin(), people.end());
// 输出结果
for (const Person& p : people) {
std::cout << p.name << " (" << p.age << ")\n";
}
// 输出:
// Bob (20)
// Alice (25)
// Charlie (30)
return 0;
}
7. 性能说明
-
std::sort
的时间复杂度为 O(NlogN)O(NlogN),其中 NN 是元素的数量。 -
std::sort
是不稳定的排序算法。如果需要稳定排序(保持相等元素的相对顺序),可以使用std::stable_sort
。
8. 完整示例
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional> // for std::greater
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 默认升序排序
std::sort(vec.begin(), vec.end());
std::cout << "Ascending: ";
for (int value : vec) {
std::cout << value << " ";
}
std::cout << "\n";
// 降序排序
std::sort(vec.begin(), vec.end(), std::greater<int>());
std::cout << "Descending: ";
for (int value : vec) {
std::cout << value << " ";
}
std::cout << "\n";
return 0;
}
总结
-
std::sort
是 C++ 中最常用的排序函数,适用于std::vector
和其他容器。 -
默认是升序排序,可以通过
std::greater
或自定义比较函数实现降序或其他规则排序。 -
对于自定义对象,可以通过重载
<
运算符或提供比较函数来排序。