c++中vector多维数组排序的方法是什么

c++
589
2024/4/25 10:34:10
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用std::sort函数对多维数组进行排序。下面是一个示例代码,对一个二维数组进行排序:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::vector<int>> arr = {{3, 2, 1}, {6, 5, 4}, {9, 8, 7}};
    
    // 对二维数组按第一列进行排序
    std::sort(arr.begin(), arr.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[0] < b[0];
    });
    
    // 输出排序后的二维数组
    for (const auto& row : arr) {
        for (int num : row) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }
    
    return 0;
}

在上面的代码中,使用std::sort函数对二维数组按第一列进行升序排序。可以根据需要修改比较函数,对其他列进行排序。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++中怎么逐行读取文件内容