从CUDA中的设备ptr获取反向迭代器

从CUDA中的设备ptr获取反向迭代器,cuda,thrust,Cuda,Thrust,对于设备向量,我可以使用它的rbegin方法来获得它的反向迭代器。但是如何直接从设备ptr构造反向迭代器呢 这可以通过使用设备ptr构造设备向量来实现,代码如下: thrust::device_ptr<int> ptr = get_ptr(); thrust::device_vector<int> tmpVector(ptr , ptr + N) thrust::inclusive_scan_by_key(tmpVector.rbegin(), tmpVector.ren

对于设备向量,我可以使用它的rbegin方法来获得它的反向迭代器。但是如何直接从设备ptr构造反向迭代器呢

这可以通过使用设备ptr构造设备向量来实现,代码如下:

thrust::device_ptr<int> ptr = get_ptr();
thrust::device_vector<int> tmpVector(ptr , ptr + N)
thrust::inclusive_scan_by_key(tmpVector.rbegin(), tmpVector.rend(), ......);
但我不知道推力::设备_向量tmpVectorptr,ptr+N是否将构造一个新向量并从ptr复制数据,或者它只是从ptr保留一个引用?推力的文件没有说明这一点


有什么想法吗?

根据Jared的评论提供答案,将此从未回答列表中删除,并将问题保留给未来的读者

要从任何类型的迭代器(包括推力::设备_ptr)生成迭代,请使用推力::生成_反向_迭代器

下面是一个简单的例子:

$ cat t615.cu
#include <thrust/device_vector.h>
#include <thrust/iterator/reverse_iterator.h>
#include <thrust/device_ptr.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <iostream>
#define DSIZE 4
int main(){

  int *data;
  cudaMalloc(&data, DSIZE*sizeof(int));
  thrust::device_ptr<int> my_data = thrust::device_pointer_cast<int>(data);
  thrust::sequence(my_data, my_data+DSIZE);
  thrust::copy_n(my_data, DSIZE, std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;
  typedef thrust::device_vector<int>::iterator Iterator;     
  thrust::reverse_iterator<Iterator> r_iter = make_reverse_iterator(my_data+DSIZE); // note that we point the iterator to the "end" of the device pointer area
  thrust::copy_n(r_iter, DSIZE, std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;
  return 0;
}
$ nvcc -arch=sm_35 -o t615 t615.cu
$ ./t615
0,1,2,3,
3,2,1,0,
$

反向迭代器的创建不会创建任何额外的数组。

推力::设备_向量tmpVectorptr,ptr+N将构造一个新向量并从ptr复制数据。您可以使用置换迭代器,使用我在回答中演示的方法,在设备ptr序列上反向迭代。@RobertCrovella,是的,我注意到了您这样做的方式,我修改了您提供的代码,并将第89行替换为推力::inclusive_scan_by_keya.rbegin,a.rend,az.rbegin,asr.rbegin,head_flag_谓词;因此,我不需要使用ra,这节省了我的时间和内存。但在我自己的程序中,我的a数组是由其他人提供的设备ptr,因此我在考虑是否可以将设备ptr传输到设备ptr向量,以便我仍然可以使用RBegi。您可以将设备ptr数组复制到设备向量。我不相信你可以将设备向量适当地包装在设备\u ptr数组周围。要从任何类型的迭代器(包括设备\u ptr)生成反向迭代器,请使用推力::make\u reverse\u迭代器函数。@JaredHoberock,谢谢,它可以工作。还有,让_reverse_迭代器创建额外的数组来实现设备的反向读取吗?