Search code examples
cudagputhrust

Mirror reordering in Thrust


I'm using thrust vector.

I'm looking for an elegant method for reordering a thrust device vector using a "mirror" ordering, (example given, couldn't find any function for that in Thrust )

For instance, Let's say my vector contain a struct, each struct contains several numbers. my vector looks like the following

[1,2]   [5,4]    [-2,5]     [6,1]     [2,6] 

after mirror reordering operation I'd like to receive the following vector (the 1st element switched with the n-th element) (the i element switched with the n-i element, etc )

[2,6]   [6,1]    [-2,5]    [5,4]    [1,2]  

Is there any elegant way doing so in Thrust ?

BTW, I was thinking about giving each struct a unique ID number and sort according to that number, that way I could "mirror " reorder the vector using sorting.


Solution

  • Use thrust::reverse:

    #include <thrust/device_vector.h>
    #include <thrust/reverse.h>
    #include <thrust/pair.h>
    #include <iostream>
    
    int main()
    {
      thrust::device_vector<thrust::pair<int,int> > vec;
    
      vec.push_back(thrust::make_pair( 1,2));
      vec.push_back(thrust::make_pair( 5,4));
      vec.push_back(thrust::make_pair(-2,5));
      vec.push_back(thrust::make_pair( 6,1));
      vec.push_back(thrust::make_pair( 2,6));
    
      std::cout << "input: " << std::endl;
      for(int i = 0; i < vec.size(); ++i)
      {
        thrust::pair<int,int> x = vec[i];
        std::cout << " [" << x.first << ", " << x.second << "]";
      }
      std::cout << std::endl;
    
      thrust::reverse(vec.begin(), vec.end());
    
      std::cout << "output: " << std::endl;
      for(int i = 0; i < vec.size(); ++i)
      {
        thrust::pair<int,int> x = vec[i];
        std::cout << " [" << x.first << ", " << x.second << "]";
      }
      std::cout << std::endl;
    
      return 0;
    }
    

    The output:

    $ nvcc reverse.cu -run
    input: 
     [1, 2] [5, 4] [-2, 5] [6, 1] [2, 6]
    output: 
     [2, 6] [6, 1] [-2, 5] [5, 4] [1, 2]