Rather than sort the arrays, sort the indices. I.e., you have
int arr[5]={4,1,3,6,2}
string arr1[5]={"a1","b1","c1","d1","e1"};
and you make
int indices[5]={0,1,2,3,4};
now you make a sort indices comparator that looks like this (just and idea, you'll probably have to fix it a little)
class sort_indices
{
private:
int* mparr;
public:
sort_indices(int* parr) : mparr(parr) {}
bool operator()(int i, int j) const { return mparr[i]<mparr[j]; }
}
now you can use the stl sort
std::sort(indices, indices+5, sort_indices(arr));
when you're done, the indices array will be such that arr[indices[0]]
is the first element. and likewise arr1[indices[0]]
is the corresponding pair.
This is also a very useful trick when you're trying to sort a large data object, you don't need to move the data around at every swap, just the indices.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…