std::sort对vector排序需传入begin()和end()迭代器及可选比较规则:默认升序;降序用std::greater或lambda;自定义类型用lambda按成员比较,注意const&参数和严格弱序。

用 std::sort 对 std::vector 排序最常用也最直接,关键是要传对迭代器范围和可选的比较规则。
对 vector 中的元素按默认顺序(如数字从小到大、字符串字典序)排序,只需传入 begin() 和 end() 迭代器:
#include <vector>
#include <algorithm>
#include <iostream>
<p>int main() {
std::vector<int> v = {5, 2, 8, 1, 9};
std::sort(v.begin(), v.end()); // 升序</p><pre class="brush:php;toolbar:false;">for (int x : v) std::cout << x << " "; // 输出:1 2 5 8 9}
把第三个参数换成 std::greater() 或 lambda 表达式即可实现降序:
立即学习“C++免费学习笔记(深入)”;
std::greater()(适用于内置类型):std::sort(v.begin(), v.end(), std::greater<>()); // 降序:9 8 5 2 1
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });只要提供明确的比较逻辑,比如按结构体某个成员排序:
struct Person {
std::string name;
int age;
};
<p>std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};
// 按年龄升序
std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
return a.age < b.age;
});注意:lambda 参数加 const& 避免不必要的拷贝,提升效率。
std::sort 要求随机访问迭代器,vector 满足,但 list 不行(得用 list::sort)a ,必须是 <code>)
基本上就这些。掌握迭代器范围 + lambda,就能应对绝大多数 vector 排序场景。
以上就是C++如何对vector进行排序?(std::sort用法示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号