排序两个对应的数组

编程入门 行业动态 更新时间:2024-10-25 01:21:47
本文介绍了排序两个对应的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的$ 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.

更多推荐

排序两个对应的数组

本文发布于:2023-11-30 10:59:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!