C++ iterators & STL

I have an multidimensional array . eg

 2 9
 1 7
 5 3
 4 8

I want to sort the array by the 1st column but the rows should always be conserved. ( 2, 9 always in same row. )
Resultant array -

 1 7
 2 9
 4 8
 5 3

Is it possible by using STL sort function ? Or will i have to rewrite a sorting function from scratch ?

1 Like

you have to define your own comparator function used in sort()
assuming data is stored in structure array with two fields c1 and c2. And sorting is done on basis of c1.
e.g.

bool comparator(const void *p, const void *q) 
{

    int l = ((struct a1 *)p)->c1;
    int r = ((struct a1 *)q)->c1; 
    return (l - r);
}

Here is how you can implement it:


struct node

{

    int x,y;

} arr[100];

int cmp(node a, node b)

{

    if(a.x < b.x) return 1;

    else if (a.x > b.x) return 0;

    else return (a.y <= b.y)? 1:0;

}

int main()

{

    int i,n=5;

    for(i=0; i < n; i++)

        scanf("%d %d",&arr[i].x,&arr[i].y);

    sort(arr,arr+n,cmp);

    for(i=0; i < n; i++)

        printf("%d %d\n",arr[i].x, arr[i].y);

    return 0;

}


Another possible implementation using pair:


int main()

{

    int i,n=5;

    pair < int,int > parr[100];

    for(i=0; i < n;i++)

        scanf("%d %d",&parr[i].first,&parr[i].second);

    sort(parr,parr+n);

    for(i=0; i < n;i++)

        printf("%d %d\n",parr[i].first, parr[i].second);

    return 0;

}
1 Like

Thank You!