C++ operating on “packed” arrays

自古美人都是妖i 提交于 2020-01-04 05:40:34

问题


Suppose that I have two, for example, float arrays a and b, an int key array k and a template mySortByKey function of my own, operating on a single array, something like

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

Is there a possibility (for example, using zip iterators and tuples of some sorts) to enable mySort operating simultaneously on a and b, so that they can be simultaneously ordered according to the key k?


回答1:


I don't think you can do that. However, you can accomplish something similar by the use of a helper array of indices.

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]];
}


来源:https://stackoverflow.com/questions/34643139/c-operating-on-packed-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!