
在C++中,对
vector进行排序最常用的方法是使用标准库中的
std::sort函数。它高效、灵活,配合自定义比较函数或Lambda表达式可以满足各种排序需求。以下是几种实用的
vector排序方法汇总。 1. 基本类型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;
}
2. 降序排序
可以通过传入
std::greater<>()实现降序排列。
std::sort(vec.begin(), vec.end(), std::greater<int>());
也可以使用Lambda表达式:
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b;
});
3. 自定义对象或结构体排序
若
vector中存储的是自定义结构体,需提供比较规则。
HyperWrite
AI写作助手帮助你创作内容更自信
54
查看详情
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;
});
4. 多条件排序
有时需要根据多个字段排序,比如先按成绩降序,成绩相同时按名字升序。
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; // 成绩相同则名字字典序小的在前
});
5. 排序部分元素
如果只想对
vector的一部分排序,可调整迭代器范围。
// 只对前5个元素排序 std::sort(vec.begin(), vec.begin() + 5);6. 使用自定义比较函数(非Lambda)
也可以定义独立函数作为比较器。
bool compareDescending(int a, int b) {
return a > b;
}
std::sort(vec.begin(), vec.end(), compareDescending);
注意:使用std::sort时,比较函数必须保证“严格弱序”(strict weak ordering),即不能有循环依赖或逻辑矛盾。 基本上就这些。掌握
std::sort搭配Lambda和比较器的用法,就能应对绝大多数
vector排序场景。不复杂但容易忽略细节,比如降序写错符号或Lambda捕获问题。
以上就是c++++中怎么对vector进行排序_c++ vector排序实用方法汇总的详细内容,更多请关注知识资源分享宝库其它相关文章!
相关标签: c++ go ai ios 排列 标准库 red sort 结构体 int double 循环 Lambda 对象 大家都在看: c++中头文件.h和.hpp的区别_C++头文件不同扩展名约定与实践 c++如何使用正则表达式_c++ 正则表达式库regex应用详解 c++中如何将int转换为string_整型与字符串相互转换方法汇总 c++中pair怎么使用_c++ pair对组使用方法详解 c++中怎么连接两个string_c++ string字符串拼接方法






发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。