C++在"打包"阵列上运行

C++ operating on "packed" arrays

本文关键字:运行 阵列 打包 C++      更新时间:2023-10-16

假设我有两个,例如float数组ab,一个int密钥数组k和一个我自己的模板mySortByKey函数,在一个数组上操作,类似

template<class T>
mySortByKey(int *k, T *a)

是否有可能(例如,使用某些类型的zip迭代器和元组)启用mySort同时在ab上操作,以便它们可以根据密钥k同时排序?

我认为你做不到。但是,您可以通过使用索引的辅助数组来实现类似的功能。

int keys[ARRAY_SIZE];
float a[ARRAY_SIZE];
float b[ARRAY_SIZE];
// Fill up the contents of keys, a, and b
// Create an array of indices.
int indices[ARRAY_SIZE];
for ( int i = 0; i < ARRAY_SIZE; ++i )
   indices[i] = i;
// Sort the indices using keys.
mySortByKey(keys, indices);
// Now access the arrays a and b indirectly, using the sorted array
// of indices as an intermediate object.
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
   float fa = a[indices[i]];
   float fb = b[indices[i]];
}