In thrust functions, how to access an element of vector with a offset

For example, in thrust::transform if the output_vector[0] needs to be computed using input_vector1[0] and input_vector2[3] then how can this be done?


There are a variety of ways to accomplish this. If you have vectors, and you are wanting the transform to work on consecutive sequences within the vectors, just at varying offsets, then you can add the desired offsets directly to the iterators passed to the thrust::transform call:

$ cat t602.cu
#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>

#define DSIZE 10

int main(){

  thrust::device_vector<int> i1(DSIZE), i2(DSIZE), o(DSIZE);
  thrust::sequence(i1.begin(), i1.end());
  thrust::sequence(i2.begin(), i2.end());
  thrust::transform(i1.begin(), i1.begin()+4, i2.begin()+3, o.begin(), thrust::plus<int>());
  thrust::copy(o.begin(), o.begin()+4, std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
$ nvcc -arch=sm_20 -o t602 t602.cu
$ ./t602
3 5 7 9

In the above example, output_vector[0] is the sum of input_vector1[0] and input_vector2[3], just as you asked. The access is consecutive, so ouput_vector[1] is the sum of input_vector1[1] and input_vector2[4]. You can do similar operations with device pointers and host pointers just by adding appropriate offsets. If instead you want a random access pattern instead of a consecutive access pattern to compute the operation on the elements of the vectors, then you could use permutation iterators.