Sort one array and two other arrays

Suppose we have three arrays a , b and c :

 int a[1000] = {3,1,5,4}; int b[1000] = {7,9,11,3}; char c[1000] = {'A','B','C','D'}; 

Array a then sorted, so it becomes:

 a == {1,3,4,5} 

Is it possible to arrange the other two arrays so that their elements are rearranged by index so that they display the location of the sorted elements in the sorted array a ? In this example, this should result in

 b == {9,7,3,11} c == {'B','A','D','C'} 

How can i achieve this?

+4
source share
2 answers

you can create an ABC class that will contain 3 fields: int a, int b, char c.
implement operator< for this class and create ABC[] appropriate size and fill it so that ABC[i] = ABC(a[i],b[i],c[i]) .

implements operator< , so it will only compare a and use sorting in an ABC array.

After sorting is complete, you have all of your elements in the correct order, just move the ABC array and fill in the rest of the arrays.

EDIT:

simplified code example [and hard coding]:

 #include <iostream> #include <algorithm> using namespace std; class ABC { public: int a,b; char c; bool operator<(const ABC& other) const { return a < other.a; } }; int main() { int a[4] = {3,1,5,4}; int b[4] = {7,9,11,3}; char c[4] = {'A','B','C','D'}; ABC abc[4]; for (int i = 0; i< 4; i++) { abc[i].a = a[i]; abc[i].b = b[i]; abc[i].c = c[i]; } sort(abc,abc+4); for (int i = 0; i < 4; i++) { a[i] = abc[i].a; b[i] = abc[i].b; c[i] = abc[i].c; } cout << "a= [" << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3] << "]" << endl; cout << "b= [" << b[0] << ", " << b[1] << ", " << b[2] << ", " << b[3] << "]" << endl; cout << "c= [" << c[0] << ", " << c[1] << ", " << c[2] << ", " << c[3] << "]" << endl; return 0; } 

works well for me on code: http://codepad.org/eCyNkyqR

+3
source

This is not exactly what you need, but you can achieve similar results using std :: map and std :: sort:

 std::map<int, std::pair<int, char> > someArray; 
0
source

All Articles