Steven
Steven

Reputation: 871

How to sort 2D array using built in sort function

I want to compare a 2D array with my custom compare function. I also reference some similar problem, but it doesn't work.

Following is what I did (compare 2D array with row and I need to use array instead of vector):

int n, dim;
int box[33][33];
bool cmp(const int a[], const int b[]){
    for(int i = 0; i < dim; i++){
        if(a[i] != b[i])
            return a[i] < b[i];
    }
    return a[dim] < b[dim];
}
int main()
{


    while(cin>>n>>dim){
        for(int i = 0; i < n; i++){
            for(int j = 0; j < dim; j++){
                cin>>box[i][j];
            }
            box[i][dim] = i+1; // store index of box
            sort(box[i], box[i]+dim);
        }

        sort(box, box + n, cmp); // This line is where I want to modify

        for(int i = 0; i < n; i++){
            for(int j = 0; j < dim; j++){
                cout<<box[i][j]<<" ";
            }
            cout<<"\n";
        }
    }
    return 0;
}

Upvotes: 0

Views: 133

Answers (1)

cigien
cigien

Reputation: 60422

You could use std::qsort in this case, by providing the appropriate comparator:

int cmp(const void *l, const void *r)
{
    const int *a = (const int*)l;
    const int *b = (const int*)r;

    for(int i = 0; i < dim; i++)
    {
        if(a[i] != b[i])
            return (a[i] > b[i]) - (a[i] < b[i]);
    }
    return (a[dim] > b[dim]) - (a[dim] < b[dim]);
}

and then calling it like this:

std::qsort(box, n, sizeof(int) * (dim + 1), cmp); 

You could also simplify the comparator like this:


int comp(const void *l, const void *r)
{
    const int *a = (const int*)l;
    const int *b = (const int*)r;

    return std::lexicographical_compare(b, b + dim + 1, a, a + dim +1);
}

Note that the arguments are in opposite order to get ascending order.

Upvotes: 1

Related Questions