如何将 thrust::transform 与独立迭代器一起使用?

How can I use a thrust::transform with independent iterators?

我在标题中的意思是,如果我想生成一个依赖于向量中两个不同值的向量,我该如何一口气做到这一点?

想象一下这个函数:

void foo(int rows, int columns)
{
    std::vector<int> blubb;
    for (int x = 0; x < rows; x++)
    {
        for (int y = 0; y < columns; y++)
        {
            blubb.push_back(x * y);
        }
    }
}

我似乎无法弄清楚如何轻松地将其转换为推力。

如果我将 thrust::transform 与 thrust::counting_iterator 一起使用,两个迭代器都会在每一步递增,但我实际上想要可能的排列:

void fooGPU(int rows, int columns)
{
    thrust::device_vector<int> blubb(rows * columns);

    thrust::transform(thrust::make_counting_iterator<int>(0),
                      thrust::make_counting_iterator<int>(rows), 
                      thrust::make_counting_iterator<int>(0), 
                      blubb.begin(), 
                      thrust::multiplies<int>());
}

我觉得这个问题有一个非常简单的解决方案,但我没有看到它。

您可以先将线性索引转换为行和列索引,然后将它们相乘。

thrust::transform(
  thrust::make_transform_iterator(thrust::make_counting_iterator(0),
                                  _1 % columns),
  thrust::make_transform_iterator(thrust::make_counting_iterator(0),
                                  _1 % columns) + rows * columns,
  thrust::make_transform_iterator(thrust::make_counting_iterator(0),
                                  _1 / columns),
  blubb.begin(), 
  _1 * _2);

您可以在此处找到有关占位符的简单示例。

https://thrust.github.io/doc/namespaceplaceholders.html