2015-02-09 71 views
0

考虑结构中的“rowPtr”,“colInd”和“values”是动态分配相同数量的元素的情况。在这种情况下,什么是最快的方式(如果可能,不进行复制!!)对colInd的元素进行排序,以便根据colInd的元素如何更改位置来交换rowPtr和value元素或更改位置。C++,同时排列单独的数组

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}; 
+0

每当你在'collnd'中做了一个改变,在其他人中做相应的改变。我误解你了吗? – ChiefTwoPencils 2015-02-09 05:02:15

+0

是在其他阵列中发生的等效更改 – 2015-02-09 05:03:08

+1

如果可能,请重新考虑您的数据结构。有一个有三个成员的结构(两个整数和一个双精度),让'csr'拥有这些结构的一个数组(或者更好的是,'std :: vector')。然后你可以使用'std :: sort'和一个合适的比较谓词。 – 2015-02-09 05:03:12

回答

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的所有元素都将重新排列。