基于C ++中另一个数组的成员对数组进行排序 [英] Sort an array based on members of another array in C++

查看:526
本文介绍了基于C ++中另一个数组的成员对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是下一个(是一个很容易显示问题的例子):

my problem is the next (is an easy example to show the problem):

我有:

int* array1;
double* array2. 

array1=new int[10];
array2=new double[10];
array1=filledWithIntegers(random);
array2=filledWithDoubles(random);

//这里我想根据array2值排序array1。我试图使用stdlib的qsort函数。
qsort(array1,6,sizeof(int),compare);

//Here I want to sort array1 based on array2 values. I´m trying to use qsort function of stdlib. qsort(array1,6, sizeof(int), compare);

关键是如何基于array2对array1的数组进行比较。

The point is how to make the compare function for order array1 based on array2.

这是不可能的要使用std库数据结构,必须直接在数组指针中完成。

It is not possible to use std library data structures, it must be done directly in the array pointers.

感谢。

推荐答案

$ c> array1 ,使用 array2 [index] 排序它们的索引以比较项目,然后重新排列 array1

Instead of sorting integers of array1, sort their indexes using array2[index] to compare items, and then re-arrange array1 in accordance with the permutation that you get back from the sort.

这是一个快速演示

#include <stdio.h>
#include <stdlib.h>

int array1[] = {1, 7, 3, 9, 5};
double array2[] = {1.1, 7.7, 3.3, 9.9, 5.5};

int compare (const void * a, const void * b) {
    double diff = array2[*(int*)a] - array2[*(int*)b];
    return  (0 < diff) - (diff < 0);
}

int main(void) {
    int perm[5], i;
    int res[5];
    for (i = 0 ; i != 5 ; i++) {
        perm[i] = i;
    }
    qsort (perm, 5, sizeof(int), compare);
    for (i = 0 ; i != 5 ; i++) {
        res[i] = array1[perm[i]];
    }
    for (i = 0 ; i != 5 ; i++) {
        printf("%d\n", res[i]);
    }
    return 0;
}

这篇关于基于C ++中另一个数组的成员对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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