商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++ vector排序方法详解

C++ vector排序方法详解

  发布于2026-03-05 阅读(0)

扫一扫,手机访问

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

c++中怎么排序一个vector_vector容器排序方法

在C++中对vector<vector<T>>(即二维vector)进行排序,可以通过std::sort函数配合自定义比较规则来实现。默认情况下,std::sort会按字典序对内层vector进行排序,但你也可以根据需要指定特定列或条件排序。

1. 按字典序排序

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}}

这会按照第一元素、再第二元素的顺序进行字典序升序排列。

2. 按某一列排序

如果想根据某一个列(比如第1列、第2列)作为主键排序,可以传入自定义比较函数:

// 按第二列升序排序
std::sort(data.begin(), data.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
    return a[1] < b[1];
});

注意要确保每个子vector至少有两个元素,否则访问a[1]会导致未定义行为。

3. 多级排序(先按列A,再按列B)

可以编写更复杂的比较逻辑实现多级排序:

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];       // 第一列相等时按第二列升序
});

4. 降序排序

只需调整比较符号即可实现降序:

// 按第一列降序
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支持比较操作,外层就能排序。注意边界检查和数据一致性,避免越界访问。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注