开发者

Sorting one array and two others array follow

开发者 https://www.devze.com 2023-04-03 08:32 出处:网络
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\'};

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 is then sorted, so it becomes:

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

Is it possible to arrange for the other two arra开发者_StackOverflow中文版ys to have their elements rearranged by index, so that they mirror the placement 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?


you can create a class ABC, which will hold 3 fields: int a, int b, char c.
implement the operator< for this class, and create a ABC[] of the approppriate size and populate it such that ABC[i] = ABC(a[i],b[i],c[i]).

implement the operator< so it will compare only a, and use sort on the ABC array.

after done sorting, you have all your elements in the desired order, just iterate the ABC array and populate the other arrays.

EDIT:

simplified [and hard coded] code sample:

#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 good for me on codepad: http://codepad.org/eCyNkyqR


It's not exactly what you need, but you can achieve similar results by using std::map and std::sort:

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

精彩评论

暂无评论...
验证码 换一张
取 消