I have a 2D array a[][40]
. I'm trying to sort it by calling std::sort
, and I have written the Compare
function. However, C++
wants me to have a std::vector
to be sorted, not a simple array and I want the sorted array to be a
itself, I don't want to create another array and save the sorting result there. It seems there are a lot of ways to achieve that. I could think of five ways, but none of them seems to be efficient and working.
1)
Directly use
std::sort(std::begin(a), std::begin(a) + something, cmp);
It doesn't work, because std::begin
doesn't know how to point to the beginning of a 2D array. Furthermore, it'd sort incorrectly even if it compiled, since a 2D array is not an array of references to arrays, but consecutive arrays (unlike Java)
Playground: https://godbolt.org/g/1tu3TF
2)
std::vector<unsigned char[40]> k(a, a + x); std::sort(k.begin(), k.end(), cmp);
Then copy everything back to
a
It doesn't work, because it's a 2D array, and it can't be sorted this way, using std::sort
. In contrast to the first trial, this one uses twice as much as memory, and copies everything twice (if it worked)!
Playground: https://godbolt.org/g/TgCT6Z
3)
std::vector<int> k(x); for (int i = 0; i < x; k[i] = i, i++); std::sort(k.begin(), k.end(), cmp2);
Then change the order of
a
to be the same ofk
;
The idea is simple, create a vector of representative "pointers", sort them (as thecmp2
function secretly accessesa
and compares the values), then makea
have the same order withk
.
In the end, the re-ordering loop will be very complex, will require a large, temporary variable. Besides, for cmp2
to access the values of a
, a global variable-pointer that points to a
must be created, which is "bad" code.
Playground: https://godbolt.org/g/EjdMo7
4)
For all
unsigned char[40]
, a struct can be created and their values can be copied to structs. Comparison and=
operators will need to be declared. After sorted, they can be copied back toa
.
It'd be a great solution if the arrays didn't have to be copied to structs to use struct's operators, but they need to be copied, so all values will be copied twice, and twice-as-needed memory will be used.
5)
For all
unsigned char[40]
, a struct that has a pointer to them can be created. They can be sorted by the pointed values, and the result can be saved to a pointer array.
It's probably the best option, although the result is a pointer array instead a
. Another reason on why it's good is it doesn't move the arrays, but the pointers.
To sum up, I need to sort the 2D array a[][40]
via std::sort
, but I haven't decided on the best way. It seems there's a "best way to do that" which I can't think of. Could you please help me?
EDIT: To clarify, I want {{3,2}{1,4}}
to become {{1,4}{3,2}}