lundi 25 mai 2020

Partially sort a C-style 2D array with std::sort

I came across this question regarding sorting the first 2 lines of an array of integers, the obvious way that came to mind was to use std::sort so I proposed a solution like:

int mat[][3] = { {4, 5, 3},
                 {6, 8, 7},
                 {9, 5, 4},
                 {2, 1, 3} }; 


std::sort(std::begin(mat[0]), std::end(mat[1]));

As you can see here it works without errors or warnings.

Meanwhile @Jarrod42 pointed out that this invokes undefined behaviour in C++ because these are two different pointers.

I inclined towards this given that in C this would be a good way to do it, (without the std::sort, std::begin and std::end of course), using a similar method of accessing the array in line, given the way 2D arrays is stored in a C program.

We pretty much agreed that it would be undefined behaviour, but what about if I use an int(*mat)[3] declaration, would it still be UB to use std::sort this way?

//...
srand(time(0));

int(*mat)[3] = (int(*)[3])malloc(sizeof(int) * 4 * 3);

for(int i = 0; i < 4 ; i++)
    for(int j = 0; j < 3; j++)
        mat[i][j] = rand() % 9 + 1;

std::sort(std::begin(mat[0]), std::end(mat[1])); //sorting the first two rows
//...

Aucun commentaire:

Enregistrer un commentaire