Sorting two corresponding arrays

后端 未结 4 1739
野性不改
野性不改 2020-11-27 16:45

I have this code here that has two arrays. It sorts arr[], so that the highest value will be in index 0. Now the second array arr1[] contai

4条回答
  •  清歌不尽
    2020-11-27 17:34

    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]

    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.

提交回复
热议问题