c++

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

小亿
120
2024-05-23 10:34:10
栏目: 编程语言

在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函数对二维数组按第一列进行升序排序。可以根据需要修改比较函数,对其他列进行排序。

0
看了该问题的人还看了