【问题标题】:removing elements from an device_vector从 device_vector 中删除元素
【发布时间】:2013-07-09 17:27:50
【问题描述】:

thrust::device_vector 值

thrust::device_vector 键;

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

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

【问题讨论】:

    标签: cuda thrust


    【解决方案1】:

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

    1. 使用thrust::remove_if (documentation) 的模板版本,将键作为模板,删除对应键为-1 的值中的元素。您将需要为谓词测试创建一个仿函数。
    2. 在键上使用 thrust::remove (documentation) 删除 -1 的值

    这是一个例子:

    #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;
    }
    

    【讨论】:

    • 另一种方法是只使用remove_if 并将keysvalues 数组压缩在一起。给remove_if 的谓词将检查元组的第一个元素是否有感兴趣的键。这可能会快一点,因为键数组的元素只需要加载一次。
    • 我在调用谓词函数时遇到了这个实现的问题。该程序没有构建并产生以下错误:“在函数范围内定义的类型不能在 global 函数模板实例化的模板参数类型中使用”关于如何纠正此问题的任何建议?
    • 我刚刚通过在 linux 上的 CUDA 9 上逐字重新编译这段代码再次测试了这个,它编译干净没有问题。你可能有一个不正确的构建环境或编译命令。或者,如果您的代码与此处发布的内容不完全相同,那么您可能引入了错误。如果没有看到它,我将无法对此发表评论。反正这里cmets的空间里可能没法梳理。我非常确信发布的代码没有任何问题。如果您有新问题,通常最好的建议是发布新问题。你可以链接到这个。
    • 你是对的......我试图尝试使用 remove_if() 来删除多个值(除了-1),其中值是在谓词函数中指定的。我会接受你的建议谢谢。
    • 您可以通过函子初始化参数(即在运行时)传递所需的值,而不是指定函子中的值。您可以在 SO 上找到推力代码,这些代码演示了将初始化值传递给函子。
    猜你喜欢
    • 2013-02-14
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2012-10-07
    • 2018-07-03
    • 2013-09-14
    • 2011-05-21
    相关资源
    最近更新 更多