溫馨提示×

vector二維數(shù)組排序的方法是什么

小億
124
2024-03-19 17:54:38
欄目: 編程語言

對于二維數(shù)組,可以通過定義一個比較函數(shù)來實現(xiàn)排序。比較函數(shù)可以按照需要對二維數(shù)組中的元素進行比較,然后使用排序算法進行排序。

以下是一個使用C++的STL進行排序的示例代碼:

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

// 比較函數(shù),按照第一列進行升序排序
bool compare(const std::vector<int>& a, const std::vector<int>& b) {
    return a[0] < b[0];
}

int main() {
    std::vector<std::vector<int>> vec = {{3, 2}, {1, 4}, {2, 1}};

    // 使用比較函數(shù)對二維數(shù)組進行排序
    std::sort(vec.begin(), vec.end(), compare);

    // 打印排序后的二維數(shù)組
    for (const auto& row : vec) {
        for (int num : row) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

在上面的代碼中,我們定義了一個比較函數(shù)compare,用于按照二維數(shù)組中每個元素的第一列進行升序排序。然后使用std::sort函數(shù)對二維數(shù)組進行排序。

如果需要按照其他列進行排序,只需修改比較函數(shù)中的比較邏輯即可。

0