Sorting a 2D array using std::sort

Hello,

Currently I am sorting a dimensional array using the following cose:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <algorithm>
#include <limits.h>
using namespace std;
#define f(i,n) for(int i=0; i<n;i++)
int boxes[30][10];
int k,d;
int comp(const void* aa, const void* bb){
	int* a = (int*)aa;
	int* b = (int*)bb;
	f(i,d)
		if(a[i]<b[i])return 1;
		else if (a[i]>b[i])return -1;
	return 0;
}

int main(){
	while(scanf("%d %d",&k, &d)!=EOF){
		f(i,k){
			fill_n(boxes[i],10,INT_MAX);
			f(j,d)
				scanf("%d",boxes[i]+j);
			sort(boxes[i],boxes[i]+d);
		}
		qsort(boxes,k,sizeof boxes[0], comp);
	}
}


I tried to use std::sort, but it complains that boxes is not of type int**. Is there a way to do this with std::sort?

Thanks,

Eric
std::sort requires that the value type of the iterator it's passed is assignable ( see http://en.cppreference.com/w/cpp/algorithm/sort for example). If you're planning to replace the call to qsort() with something like sort(boxes, boxes+k), you're passing pointers to 1D arrays of 10 int each, and raw C-style arrays are not assignable.

To make them assignable, you can wrap them in structs (or some other suitable class types), which would make you reinvent std::array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <array>
#include <algorithm>
#include <climits>
using namespace std;

int main(){
    array< array<int, 10>, 30 > boxes = {};
    int k,d;

    while(cin >> k >> d) {

        for(int i = 0; i < k; ++i) {
            fill(boxes[i].begin(), boxes[i].end(), INT_MAX);
            for(int j = 0; j < d; ++j)
                cin >> boxes[i][j];
            sort(boxes[i].begin(), boxes[i].begin() + d); // sort the first d elemenents
        }
        sort(boxes.begin(), boxes.begin() + k); // sort the first k  rows

        for(auto& row : boxes) { // output
            for(auto& n : row)
                cout << n << ' ';
            cout << '\n';
        }
    }
}


you could use vectors, too.
Topic archived. No new replies allowed.