从device_vector中删除元素

时间:2013-07-11 12:29:06

标签: cuda thrust

thrust :: device_vector values

thrust :: device_vector keys;

初始化后,键包含一些等于-1的元素。我想删除键中的元素和值的相同位置。

但我不知道如何处理并行?

1 个答案:

答案 0 :(得分:3)

可能有很多方法可以做到这一点。一种可能的方式:

  1. 使用模板版thrust::remove_ifdocumentation),将键作为模板,删除相应键为-1的值中的元素。您需要为谓词测试创建一个仿函数。
  2. 在键上使用thrust::removedocumentation)删除-1的值
  3. 以下是一个例子:

    #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;
    }
    
相关问题