对两个对应的数组进行排序

对两个对应的数组进行排序

本文介绍了对两个对应的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里的代码有两个数组.它对 arr[] 进行排序,以便最高值将在索引 0 中.现在第二个数组 arr1[] 包含字符串,我希望代码应用任何将 arr[] 更改为 arr1[].这样 arr[0] 将返回 6,而 arr1[0] 将返回字符串 "d1".请注意 "d1"6 的索引如何相同?排序后,我希望相同的值仍然具有它们的字符串对应项.

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[] contains strings, I'd like the code to apply whatever changes where made to arr[] to arr1[]. So that arr[0] would return 6, while arr1[0] would return the string "d1". Notice how "d1" was at the same index as 6? After sorting I'd like the same values to still have their string counterparts.

我该怎么做?

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <functional>
using namespace std;

int main() {
  int arr[ 5 ] = { 4, 1, 3, 6, 2 };
  string arr1[ 5 ] = { "a1", "b1", "c1", "d1", "e1" };

  std::sort( arr, arr + 5, std::greater< int >() );
  cout << arr[0] << arr1[0] << endl;

  system("pause");
}

推荐答案

与其对数组进行排序,不如对索引进行排序.即,你有

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"};

你做

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]; }
}

现在你可以使用 stl 排序了

now you can use the stl sort

std::sort(indices, indices+5, sort_indices(arr));

完成后,索引数组将使得 arr[indices[0]] 是第一个元素.同样 arr1[indices[0]] 是对应的对.

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.

这篇关于对两个对应的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:58