There are examples of sorting vectors or dynamically allocated arrays but I couldn’t find any help regarding static arrays. Let’s say I have an array
int array[10][10];
and a compare function,
bool compare(const int (*a)[10], const int (*b)[10]);
When I call it like this,
std::sort(array, array + 10, compare);
I have compilation errors: error: cannot convert 'int*' to 'const int (*)[10]' in argument passing
I tried many ways, casting array to (void**) in sort function but then I have segmentation fault. My problem is using arrays as function parameters I guess but I couldn’t figure out how to use this std::sort. Otherwise, I will have to write my own sort function.
When
std::sortis called on a container of elements of typeT, the comparison function needs to receive arguments of typeTorconst T&. In this case, you have a 2-dimensional array, so the type of elements is a 1-dimensional arrayint[10]. Since 1-dimensional arrays decay to pointers,comparecan be:or equivalently:
This will fix the error you got, but your code still won’t work:
std::sortneeds the container elements to be assignable (or movable in C++11), but arrays are not assignable.You can use
std::vector<std::vector<int> >instead as people have suggested. Note that your fear of performance problems is misguided: Even if sorting a two-dimensional array was possible, it would involve a lot of copying of one-dimensional arrays which would take a long time. Swapping vectors, on the other hand, is done by simply swapping pointers which is faster. In general, you should not make assumptions about performance if you haven’t tested it first.