I have a table stored in memory. How to sort it based on column?

I have a table stored in continuous memory. It should remain in this format after sorting.

For instance:

int table[5][3] = {
    { 60, 5, 10 },
    { 0, 200, 15 },
    { 55, 50, 365 },
    { 4, 7, 78 },
    { 555, 8, 11 },
};

Except for much larger (the largest in bytes is about 27 KB). Each cell is always int32, and all rows have the same number of columns.

Let's say that I want to sort it based on the first column, so the result should be equivalent:

    { 0, 200, 15 },
    { 4, 7, 78 },
    { 55, 50, 365 },
    { 60, 5, 10 },
    { 555, 8, 11 },

What is the best way to do this? I think there is a better way than converting this to std::list, call sort()and convert back.

Also, something built into C ++ where I just need to call some function would be better.

+3
3

std::sort , .

std::qsort :

int cmp_first_column(const void *lhs_, const void *rhs_) {
    // optimize this to taste
    const int *lhs = static_cast<const int*>(lhs_);
    const int *rhs = static_cast<const int*>(rhs_);
    if (lhs[0] < rhs[0]) return -1;
    if (lhs[0] > rhs[0]) return 1;
    return 0;
}

std::qsort(table, 5, 3*sizeof(int), cmp_first_colum);

, std::qsort , , , .

int[3] int[3] . , std::sort . , , , , .

+3

- , .

() , , ( , ), . , (, , ). , , .

OTOH, , ( ) , , qsort ( ). , qsort ++. , , , .

+2

, , , , , , .

, , , a > b .., , . , .

-2

Source: https://habr.com/ru/post/1795118/


All Articles