gpt4 book ai didi

sorting - 推力::sort_by_key:如何将结果存储在单独的数组中?

转载 作者:行者123 更新时间:2023-12-04 05:15:04 25 4
gpt4 key购买 nike

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

thrust::sort_by_key(thrust::device_ptr<int>(keys), 
thrust::device_ptr<int>(keys + numKeys),
thrust::device_ptr<int>(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());

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

现在 perm将返回 valueskeys index 持有的排序顺序无需更改原始数据的顺序。

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

关于sorting - 推力::sort_by_key:如何将结果存储在单独的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14393113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com