问题描述
我在向量中具有这样的预定义元素序列,该向量包含数千个元素:
207.1 226.1 229.1 231.1 210.1 239.1 235.1 201.1 247.1 245.1 197.1 203.1 246.1 249.1 196.1 248.1 244.1 238.1
在不同的向量中,我具有与预定义向量相同的元素,但是以这种分散的方式
226.1 225.1 205.1 220.1 220.1 237.1 226.1 212.1 212.1 205.1 205.1 202.1 202.1 192.1 192.1 192.1 191.1 191.1 192.1 192.1 192.1
现在,我想汇总散乱向量中的元素,以便保持预定义向量的顺序,因此结果应该像这样
207.1 207.1 207.1 226.1 226.1 226.1 226.1 229.1 229.1 229.1 229.1。 。 。 有没有办法使用CUDA推力来做到这一点?
解决方法
我会做一些我认为必要的假设:
-
您的第一个“预定义”序列没有重复项。如果有重复项,并且不相邻,我将无法提出订购策略
-
您的第二个“散布”序列没有任何元素,这些元素也不在第一个序列中。如果有的话,我不知道在哪里放置或如何订购
基于这些假设,使用上面对“第一”和“第二”序列的定义,这是一种可能的方法:
-
对于第一个序列,请提供长度相同的向量(“索引”序列),以指示值的索引:
207.1 226.1 229.1 231.1 ... 0 1 2 3 ...
-
执行
sort_by_key
来排序第一个序列。现在将对索引序列进行加扰。 -
使用有序的第一个序列,在第二个序列上使用
thrust::lower_bound
,以查找它匹配的第一个序列的哪个值。 -
使用第二个序列中的每个元素的匹配值索引(通过
thrust::permutation_iterator
,通过匹配值索引sort_by_key
使用第二个序列。
这里是一个例子:
$ cat t41.cu
#include <thrust/sort.h>
#include <thrust/binary_search.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/iterator/permutation_iterator.h>
#include <iostream>
#include <cstdlib>
const int max_samples_per_element = 4;
typedef float dt;
typedef int it;
int main(){
// seq 1 and 2 data setup
// host
dt seq_1[] = {207.1,226.1,229.1,231.1,210.1,239.1,235.1,201.1,247.1,245.1,197.1,203.1,246.1,249.1,196.1,248.1,244.1,238.1};
it seq_1_sz = sizeof(seq_1)/sizeof(seq_1[0]);
thrust::host_vector<dt> seq_2_hv;
for (int i = seq_1_sz-1; i >= 0; i--){
int element_samples = rand()%max_samples_per_element;
element_samples++;
for (int j = 0; j < element_samples; j++)
seq_2_hv.push_back(seq_1[i]);
}
// device
thrust::device_vector<dt> seq_2_dv = seq_2_hv;
thrust::device_vector<dt> seq_1_dv(seq_1,seq_1+seq_1_sz);
thrust::device_vector<it> index(seq_1_dv.size());
thrust::device_vector<it> index2(seq_2_dv.size());
thrust::sequence(index.begin(),index.end());
//process data
thrust::sort_by_key(seq_1_dv.begin(),seq_1_dv.end(),index.begin());
thrust::lower_bound(seq_1_dv.begin(),seq_2_dv.begin(),seq_2_dv.end(),index2.begin());
auto my_pi = thrust::make_permutation_iterator(index.begin(),index2.begin());
thrust::sort_by_key(my_pi,my_pi+index2.size(),seq_2_dv.begin());
// display results
thrust::host_vector<dt> result = seq_2_dv;
thrust::copy_n(seq_1,seq_1_sz,std::ostream_iterator<dt>(std::cout,","));
std::cout << std::endl;
thrust::copy(result.begin(),result.end(),"));
std::cout << std::endl;
}
$ nvcc -arch=sm_35 -o t41 t41.cu -O3 -lineinfo -Wno-deprecated-gpu-targets -std=c++14
$ ./t41
207.1,238.1,207.1,$
我并不是说上面的代码没有缺陷,也不适合任何特定目的。我的目的是演示一种可能的方法,而不提供经过全面测试的代码。