C++中vector排序常用std::sort,配合比较函数或Lambda可实现升序、降序、自定义类型、多条件及部分排序,需注意严格弱序规则。

在C++中,对
vector
std::sort
vector
对于存储基本类型(如
int
double
vector
std::sort
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> vec = {5, 2, 8, 1, 9};
std::sort(vec.begin(), vec.end());
for (int x : vec) {
std::cout << x << " ";
}
// 输出:1 2 5 8 9
return 0;
}
可以通过传入
std::greater<>()
std::sort(vec.begin(), vec.end(), std::greater<int>());
也可以使用Lambda表达式:
立即学习“C++免费学习笔记(深入)”;
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b;
});
若
vector
struct Student {
std::string name;
int score;
};
std::vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 70}};
// 按分数从高到低排序
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score > b.score;
});
如果想按名字字典序排序:
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.name < b.name;
});
有时需要根据多个字段排序,比如先按成绩降序,成绩相同时按名字升序。
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score; // 成绩高的在前
}
return a.name < b.name; // 成绩相同则名字字典序小的在前
});
如果只想对
vector
// 只对前5个元素排序 std::sort(vec.begin(), vec.begin() + 5);
也可以定义独立函数作为比较器。
bool compareDescending(int a, int b) {
return a > b;
}
std::sort(vec.begin(), vec.end(), compareDescending);
std::sort
std::sort
vector
以上就是c++++中怎么对vector进行排序_c++ vector排序实用方法汇总的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号