如何将device_vector的每个元素减一个常量?

问题描述 投票:5回答:2

我正在尝试使用thrust::transformdevice_vector的每个元素中减去一个常量值。如您所见,最后一行是不完整的。我正在尝试从所有元素中减去常数fLowestVal,但不知道精确度如何。

thrust::device_ptr<float> pWrapper(p);
thrust::device_vector<float> dVector(pWrapper, pWrapper + MAXX * MAXY);
float fLowestVal = *thrust::min_element(dVector.begin(), dVector.end(),thrust::minimum<float>());

// XXX What goes here?
thrust::transform(...);

另一个问题:在device_vector上进行更改后,这些更改是否也适用于p数组?

谢谢!

cuda thrust
2个回答
6
投票

您可以通过将device_vector与占位符表达式结合使用,从for_each的每个元素中减少一个常量值:

#include <thrust/functional.h>
...
using thrust::placeholders;
thrust::for_each(vec.begin(), vec.end(), _1 -= val);

[异常的_1 -= val语法意味着创建一个未命名的函子,其作用是将其第一个参数减val_1位于名称空间thrust::placeholders中,我们可以通过using thrust::placeholders指令访问该名称空间。

您也可以通过将for_eachtransform与您自己提供的自定义函子结合起来来进行此操作,但这更冗长。


0
投票

在广泛的上下文中可能有用的一个选项是使用Thrust的奇特迭代器之一作为thrust::transform的参数。在这里,您将与thrust::minus二进制函数对象一起执行操作,如下所示:

#include <thrust/transform.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/functional.h>
...
thrust::transform(vec.begin(), vec.end(),
                  vec.begin(),
                  thrust::make_constant_iterator(value),
                  thrust::minus<float>());

花式迭代器的文档可以找到here

© www.soinside.com 2019 - 2024. All rights reserved.