C ++,同时对单独的数组进行排序

时间:2015-02-09 04:59:41

标签: c++ arrays sorting struct

考虑结构中“rowPtr”,“colInd”和“values”动态分配相同数量元素的情况。在这种情况下,最快的方法是什么(如果可能的话,没有复制!!)对colInd的元素进行排序,以便交换rowPtr和value元素,或者根据colInd元素如何改变位置来改变位置。

struct csr
{
    int rows;
    int cols;
    int nzmax;
    int *rowPtr;
    int *colInd;
    double *values;
};
// A simple example without a struct. Just based on arrays
double values[10] = {0.2135, 0.8648, 7, 0.3446, 0.1429, 6, 0.02311, 0.3599, 0.0866, 8 };
int rowPtr[10] = { 0, 3, 6, 10, 2 -1, 24, -4, 1, 11 };
int colInd[10] = { 0, 2, 4, 1, 2, 3, 0, 1, 2, 4 };
// sort colInd and simultaneously change positions in rowPtr and values
//After sorting
Values = {0.214, 0.023, 0.345, 0.360, 0.865, 0.143, 0.087, 6.0};
rowPtr = {0, 24, 10, -4, 3, 2, 1, -1};
colInd  = {0, 0, 1, 1, 2, 2, 2, 3};

1 个答案:

答案 0 :(得分:0)

我建议将三个数组放入struct数组中,并对struct数组进行排序。

struct csr_data
{
    int rowPtr;
    int colInd;
    double value;
};

struct csr
{
    int rows;
    int cols;
    int nzmax;
    csr_data* data_array;
};

您可以使用三个成员变量中的任何一个对csr_data数组进行排序。对它们进行排序后,无论您使用哪个成员对数据进行排序,都会重新排列csr_data的所有元素。