C++ 二維陣列按列排序 Sort 2D array by row

5 2 0 (a)
7 4 0 (b)
4 8 7 (c)
4 8 7 (c)
5 2 0 (a)
7 4 0 (b)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(vector<int> v1, vector<int> v2){
    return v1[0] < v2[0];
}
int main(){
    ios::sync_with_stdio(0), cin.tie(0);
    vector<vector<int>> v{{5, 2, 0},
                          {7, 4, 0},
                          {4, 8, 7}};
    int m = v.size(); //rows
    int n = v[0].size(); //columns
    cout << "Before:\n";
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++)
            cout << v[i][j] << ' ';
        cout << '\n';
    }
    sort(v.begin(), v.end(), cmp);
    cout << "\nAfter:\n";
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++)
            cout << v[i][j] << ' ';
        cout << '\n';
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。