排序两个对应的数组 [英] Sorting two corresponding arrays

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

问题描述

我有这样的$ C $这里C,它有两个数组。它排序的改编[] ,从而使最高值将在指数0。现在第二个数组的 ARR1 [] 包含字符串,我想在code适用无论在哪里的改编[] 作出的 ARR1 [] 的变化。这样的改编[0] 将返回6,而 ARR1 [0] 将返回字符串D1。请注意如何D1是相同的索引在 6 ?排序后我想相同的价值观仍然有它们的字符串对应。

我将如何去这样做呢?

 的#include<&iostream的GT;
#包括LT&;&了iomanip GT;
#包括LT&;&算法GT;
的#include<功能>
使用命名空间std;
主要(){
INT ARR [5] = {4,1,3,6,2};串ARR1 [5] = {A1,B1,C1,D1,E1};的std ::排序(ARR,编曲+ 5,性病::更大< INT>());
COUT<<改编[0]&下;&下; ARR1 [0]&下;&下; ENDL;系统(暂停);
}


解决方案

而不是数组进行排序,指数排序。即,你有

  INT ARR [5] = {4,1,3,6,2}
串ARR1 [5] = {A1,B1,C1,D1,E1};

和您

  INT指数[5] = {0,1,2,3,4};

现在你做一个排序指标比较,看起来像这样(只是和想法,你可能必须解决它一点点)

 类sort_indices
{
   私人的:
     INT * mparr;
   上市:
     sort_indices为(int *帕尔):mparr(帕尔){}
     布尔运算符()(诠释我,诠释J)const的{返回mparr [1] - ; mparr [J]。 }
}

现在你可以使用STL排序

 的std ::排序(指数,指数+ 5,sort_indices(ARR));

当您完成后,指数阵列将是这样的:改编[指数[0] 是第一要素。同样地 ARR1 [指数[0] 是相应的一对。

这也是当你试图理清一个大的数据对象,你不需要在每一个交换四处移动的数据,仅仅是指数一个非常有用的技巧。

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.

How would I go about doing this?

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


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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆