How to use the sort function to sort a 2D array in C++?

To sort a two-dimensional array in C++, you can use the sort function along with a custom comparison function. Here is an example code:

#include <iostream>
#include <algorithm>
using namespace std;

bool compareArrays(const int* arr1, const int* arr2, int size) {
    for (int i = 0; i < size; i++) {
        if (arr1[i] < arr2[i]) {
            return true;
        } else if (arr1[i] > arr2[i]) {
            return false;
        }
    }
    return false;
}

int main() {
    const int rows = 3;
    const int cols = 4;
    int arr[rows][cols] = {{1, 4, 2, 3}, {5, 6, 7, 8}, {9, 10, 11, 12}};

    sort(&arr[0][0], &arr[0][0] + rows * cols, [&](const int& a, const int& b) {
        int row1 = (int)(&a - &arr[0][0]) / cols;
        int col1 = (int)(&a - &arr[0][0]) % cols;
        int row2 = (int)(&b - &arr[0][0]) / cols;
        int col2 = (int)(&b - &arr[0][0]) % cols;
        return compareArrays(arr[row1], arr[row2], cols);
    });

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

In this example, we begin by defining a compareArrays function to compare the relative sizes of two one-dimensional arrays. Then, in the main function, we use the sort function to sort a two-dimensional array. Here, we specify a custom comparison function that compares the elements of the two-dimensional array based on row priority.

Please note that in order to obtain the row and column indices of elements in the comparison function, we use pointer arithmetic to calculate the position of elements in the two-dimensional array.

Finally, we use two nested loops to iterate through and output the sorted two-dimensional array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds