C++ CUDA Thrust 如何制作一个包含所有偶数索引然后所有奇数索引的迭代器?

C++ CUDA Thrust how to make an iterator that contains all even indices then all odd indices?

例如,如果数组有 6 个元素,则此迭代器将像:[0, 2, 4, 1, 3, 5]

我知道 counting_iteratorconstant_iterator,但是如何创建上面的迭代器?我觉得跟transform_iterator有关系,但不知道怎么回事。

这是一种可能的方法。你可以在里面使用 permutation_iteratortransform_iterator,像这样:

$ cat t87.cu
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <cstdlib>
#include <iostream>

struct my_even_odd{
        int s;
        my_even_odd(size_t _s) {s = (_s+1)>>1;}
        __host__ __device__
        int operator()(int i){
                if (i < s) return 2*i;
                return 2*(i-s)+1;}
};

int main(int argc, char *argv[]){
  int ds = 7;
  if (argc > 1) ds = atoi(argv[1]);
  thrust::device_vector<int> d(ds);
  thrust::device_vector<int> r(d.size());
  thrust::sequence(d.begin(), d.end());
  thrust::copy_n(thrust::make_permutation_iterator(d.begin(), thrust::make_transform_iterator(thrust::counting_iterator<int>(0), my_even_odd(d.size()))), d.size(), r.begin());
  thrust::host_vector<int> h_r = r;
  thrust::copy(h_r.begin(), h_r.end(), std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;
}
$ nvcc -o t87 t87.cu
$ ./t87 6
0,2,4,1,3,5,
$ ./t87 7
0,2,4,6,1,3,5,
$

我认为这应该适用于偶数和奇数向量大小,但是我没有仔细测试它并且没有声称它是 defect-free。