C++程序 在二维数组中按行排序
在C++中,我们经常会使用二维数组来存储数据。如果想要按行进行排序,可以采用以下方法。
方法一:手写排序函数
我们可以手写一个排序函数来对二维数组中的每一行进行排序。具体代码如下:
#include <algorithm>
#include <iostream>
using namespace std;
bool cmp(int a, int b) {
    return a < b;
}
void sortRow(int **matrix, int row, int col) {
    for (int i=0; i<row; i++) {
        sort(matrix[i], matrix[i]+col, cmp);
    }
}
int main() {
    int row = 3, col = 4;
    int **matrix = new int*[row];
    for (int i=0; i<row; i++) {
        matrix[i] = new int[col];
        for (int j=0; j<col; j++) {
            matrix[i][j] = rand()%10;
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    sortRow(matrix, row, col);
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    for (int i=0; i<row; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
    return 0;
}
在以上代码中,我们手写了一个排序函数cmp来比较两个元素的大小,并使用sort函数对每一行进行排序。
方法二:使用vector
我们还可以使用C++中的STL库vector来实现对二维数组中每一行的排序。具体代码如下:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool cmp(int a, int b) {
    return a < b;
}
void sortRow(vector<vector<int>> &matrix) {
    for (auto &row : matrix) {
        sort(row.begin(), row.end(), cmp);
    }
}
int main() {
    int row = 3, col = 4;
    vector<vector<int>> matrix(row, vector<int>(col, 0));
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            matrix[i][j] = rand()%10;
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    sortRow(matrix);
    for (auto row : matrix) {
        for (auto num : row) {
            cout << num << " ";
        }
        cout << endl;
    }
    return 0;
}
在以上代码中,我们使用vector<vector
方法三:使用自定义比较函数
除了手写排序函数和使用vector外,我们还可以使用STL库的sort函数的一个重载形式,使用自定义比较函数来比较每一行的大小。具体代码如下:
#include <algorithm>
#include <iostream>
using namespace std;
bool cmp(const vector<int> &row1, const vector<int> &row2) {
    return row1[0] < row2[0];
}
void sortRow(vector<vector<int>> &matrix) {
    sort(matrix.begin(), matrix.end(), cmp);
}
int main() {
    int row = 3, col = 4;
    vector<vector<int>> matrix(row, vector<int>(col, 0));
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            matrix[i][j] = rand()%10;
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    sortRow(matrix);
    for (auto row : matrix) {
        for (auto num : row) {
            cout << num << " ";
        }
        cout << endl;
    }
    return 0;
}
在以上代码中,我们使用了一个自定义的比较函数cmp,每次比较每一行的第一个元素的大小,然后使用sort函数来对每一行进行排序。
结论
以上是三种在C++中对二维数组按行排序的方法,分别是手写排序函数、使用vector和使用自定义比较函数。在实际使用中,可以根据具体情况选择不同的方法来实现排序操作。
 极客笔记
极客笔记