答案:C++中通过std::sort和lambda表达式对二维vector排序,支持字典序、指定列、多级及降序排序,需注意元素访问越界问题。

在C++中对vector<vector<T>>(即二维vector)进行排序,可以通过std::sort函数配合自定义比较规则来实现。默认情况下,std::sort会按字典序对内层vector进行排序,但你也可以根据需要指定特定列或条件排序。
vector的比较默认是按字典序进行的,因此可以直接使用std::sort:
#include <vector>
#include <algorithm>
#include <iostream>
std::vector<std::vector<int>> data = {{3, 2}, {1, 4}, {2, 1}};
std::sort(data.begin(), data.end());
// 结果:{{1,4}, {2,1}, {3,2}}
这会按照第一元素、再第二元素的顺序进行字典序升序排列。
如果想根据某一个列(比如第1列、第2列)作为主键排序,可以传入自定义比较函数:
立即学习“C++免费学习笔记(深入)”;
// 按第二列升序排序
std::sort(data.begin(), data.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
return a[1] < b[1];
});
注意要确保每个子vector至少有两个元素,否则访问a[1]会导致未定义行为。
可以编写更复杂的比较逻辑实现多级排序:
std::sort(data.begin(), data.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
if (a[0] != b[0])
return a[0] < b[0]; // 先按第一列升序
return a[1] < b[1]; // 第一列相等时按第二列升序
});
只需调整比较符号即可实现降序:
// 按第一列降序
std::sort(data.begin(), data.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
return a[0] > b[0];
});
基本上就这些。关键是掌握std::sort和lambda表达式结合使用的方式,灵活控制排序逻辑。只要内层vector支持比较操作,外层就能排序。注意边界检查和数据一致性,避免越界访问。
以上就是c++++中怎么排序一个vector_vector容器排序方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号