2

I am currently sorting values by key the following way

thrust::sort_by_key(thrust::device_ptr<int>(keys), 
                    thrust::device_ptr<int>(keys + numKeys),
                    thrust::device_ptr<int>(values);

which sorts the "values" array according to "keys".

Is there a way to leave the the "values" array untouched and instead store the result of sorting "values" in a separate array?

Thanks in advance.

4

1 回答 1

3

There isn't a direct way to do what you are asking. You have two options to functionally achieve the same thing.

The first is make a copy of the values array before the call, leaving you with a sorted and unsorted version of the original data. So your example becomes

thrust::device_vector<int> values_sorted(thrust::device_ptr<int>(values),
                                     thrust::device_ptr<int>(values + numKeys));

thrust::sort_by_key(thrust::device_ptr<int>(keys), 
                    thrust::device_ptr<int>(keys + numKeys),
                    values_sorted.begin());

The second alternative is not to pass the values array to the sort at all. Thrust has a very useful permutation iterator which allows for seamless permuted access to an array without modifying the order in which that array is stored (so an iterator based gather operation, if you will). To do this, create an index vector and sort that by key instead, then instantiate a permutation iterator with that sorted index, something like

typedef thrust::device_vector<int>::iterator iit;

thrust::device_vector<int> index(thrust::make_counting_iterator(int(0)),
                                 thrust::make_counting_iterator(int(numKeys));    

thrust::sort_by_key(thrust::device_ptr<int>(keys), 
                    thrust::device_ptr<int>(keys + numKeys),
                    index.begin());


thrust::permutation_iterator<iit,iit> perm(thrust::device_ptr<int>(values),
                                           index.begin());

Now perm will return values in the keys sorted order held by index without ever changing the order of the original data.

[standard disclaimer: all code written in browser, never compiled or tested. Use at own risk]

于 2013-01-18T09:14:42.353 回答