Sorting 按关键字排序:如何将结果存储在单独的数组中?

Sorting 按关键字排序:如何将结果存储在单独的数组中?,sorting,cuda,thrust,Sorting,Cuda,Thrust,我目前正在按以下方式按键对值进行排序 thrust::sort_by_key(thrust::device_ptr<int>(keys), thrust::device_ptr<int>(keys + numKeys), thrust::device_ptr<int>(values); 推力::按按键排序(推力::设备ptr(按键), 推力:装置(钥匙+钥匙), 推力:装置的p

我目前正在按以下方式按键对值进行排序

thrust::sort_by_key(thrust::device_ptr<int>(keys), 
                    thrust::device_ptr<int>(keys + numKeys),
                    thrust::device_ptr<int>(values);
推力::按按键排序(推力::设备ptr(按键),
推力:装置(钥匙+钥匙),
推力:装置的ptr(值);
它根据“键”对“值”数组进行排序

有没有办法让“values”数组保持不变,而是将“values”排序结果存储在一个单独的数组中


提前感谢。

没有一种直接的方法来实现你的要求。你有两种选择来实现同样的功能

第一种方法是在调用之前复制一个values数组,留下原始数据的已排序和未排序版本

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());
推力::设备向量值排序(推力::设备ptr(值),
推力:装置(数值+数值);
推力::按按键排序(推力::设备ptr(按键),
推力:装置(钥匙+钥匙),
值_sorted.begin());
第二种选择是根本不将数组中的值传递给sort。推力有一个非常有用的置换迭代器,它允许无缝置换访问数组,而无需修改数组的存储顺序(因此,如果愿意,可以使用基于迭代器的聚集操作)。为此,请创建一个索引向量并按键进行排序,然后用排序后的索引实例化置换迭代器,如

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());
typedef推力::设备向量::迭代器iit;
推力::设备向量索引(推力::生成计数迭代器(int(0)),
推力:生成计数迭代器(int(numKeys));
推力::按按键排序(推力::设备ptr(按键),
推力:装置(钥匙+钥匙),
index.begin());
推力::置换迭代器perm(推力::设备ptr(值),
index.begin());
现在,
perm
将返回
中的
,排序顺序由
索引
持有,而不改变原始数据的顺序


[标准免责声明:所有在浏览器中编写的代码,从未编译或测试过。使用风险自负]

谢谢您的回复!我以前曾想过用第一种方法进行排序,但我担心会带来额外的开销。我将尝试您的第二种方法,看看结果如何。但是,由于“推力”不提供此类功能,我担心自己实现基数排序可能是解决此问题的最快方法。。。