removing elements from an device_vector

2019-02-19 19:19发布

问题:

thrust::device_vector values

thrust::device_vector keys;

After initialization, keys contains some elements equal to -1. I wanted to delete the elements in keys and in the same position of values.

But I do not know how to deal with it parallel?

回答1:

There are probably many ways to do this. One possible way:

  1. use the stencil version of thrust::remove_if (documentation), with the keys as your stencil, removing the elements in values where the corresponding key is -1. You will need to create a functor for the predicate test.
  2. use thrust::remove (documentation) on the keys to remove the values that are -1

Here's an example:

#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/remove.h>
#include <thrust/sequence.h>

#define N 12
typedef thrust::device_vector<int>::iterator dintiter;

struct is_minus_one
{
  __host__ __device__
  bool operator()(const int x)
  {
    return (x == -1);
  }
};

int main(){

  thrust::device_vector<int> keys(N);
  thrust::device_vector<int> values(N);

  thrust::sequence(keys.begin(), keys.end());
  thrust::sequence(values.begin(), values.end());

  keys[3] = -1;
  keys[9] = -1;

  dintiter nve = thrust::remove_if(values.begin(), values.end(), keys.begin(), is_minus_one());
  dintiter nke = thrust::remove(keys.begin(), keys.end(), -1);

  std::cout << "results  values:" << std::endl;
  thrust::copy(values.begin(), nve, std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl << "results keys:" << std::endl;
  thrust::copy(keys.begin(), nke, std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl;

  return 0;
}


标签: cuda thrust