How to sort a two-dimensional array by column in C++?

To sort a C++ two-dimensional array by column, you can use the std::sort function along with a custom comparison function.

First, let’s consider a 2D array called arr with m rows and n columns. We must define a custom comparison function cmp that will be used to compare two elements.

bool cmp(const vector<int>& a, const vector<int>& b) {
    return a[col] < b[col];
}

In which col specifies which column to sort by. The return value of the comparison function is true if a should come before b, and false if a should come after b.

Then, we can use the std::sort function in the main function to sort the two-dimensional array by column. If we want to sort by the i-th column, we need to set col to i.

int main() {
    int m = arr.size();  // 行数
    int n = arr[0].size();  // 列数
    int col = i;  // 按第i列进行排序

    std::sort(arr.begin(), arr.end(), cmp);
    
    // 输出排序后的二维数组
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            std::cout << arr[i][j] << " ";
        }
        std::cout << std::endl;
    }
    
    return 0;
}

This way, you can sort a two-dimensional array column by column. Please note that ‘arr’ here is a two-dimensional vector, and its rows and columns can be modified according to the actual situation.

bannerAds