获取CUDA推力::transform运算符()函数内向量的索引
Get index of vector inside CUDA thrust::transform operator() function
在CUDA Thrust变换中,是否可以在函数内部获得传递到运算符()函数中的向量的索引?
比如说,我们有
struct op{
float operator()(const float& f){
//do something like return the index
}
};
vector<float> v(100);
thrust::transform(v.begin(),v.end(),v.begin(),op());
如何在运算符()中获取向量的索引?基本上,我想要一种简单的方法来制作CUDA中的单位矩阵。
可能有很多方法可以做到这一点。一种方法是:
- 使用
thrust::sequence
创建与数据向量长度相同的索引向量(或者只使用counting_iterator
) - 使用
zip_iterator
返回thrust::tuple
,组合数据向量和索引向量,返回数据项的元组及其索引 - 定义运算符
op()
以将特定元组作为其参数之一 - 在运算符中,使用
thrust::get<>
从元组中检索数据元素或根据需要检索索引
您可以在推力快速启动指南中阅读更多关于这些概念的内容。
EDIT:针对下面的问题,这里有一个工作示例。虽然这实际上并不使用任何device_vector
,但如果我们在GPU上执行此操作(使用device_vector
),则唯一会生成任何重要GPU活动的活动将是对thrust::transform
的调用,即GPU上只有1个"pass"。
(是的,推力::序列调用也会生成GPU内核,但我只是用它来为这个例子创建一些数据)。
#include <thrust/host_vector.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#define N 30
#define SELECT 3
typedef thrust::tuple<int, int> tpl2int;
typedef thrust::host_vector<int>::iterator intiter;
typedef thrust::counting_iterator<int> countiter;
typedef thrust::tuple<intiter, countiter> tpl2intiter;
typedef thrust::zip_iterator<tpl2intiter> idxzip;
struct select_unary_op : public thrust::unary_function<tpl2int, int>
{
__host__ __device__
int operator()(const tpl2int& x) const
{
if ((x.get<1>() %SELECT) == 0)
return x.get<0>();
else return -1;
}
};
int main() {
thrust::host_vector<int> A(N);
thrust::host_vector<int> result(N);
thrust::sequence(A.begin(), A.end());
thrust::counting_iterator<int> idxfirst(0);
thrust::counting_iterator<int> idxlast = idxfirst +N;
idxzip first = thrust::make_zip_iterator(thrust::make_tuple(A.begin(), idxfirst));
idxzip last = thrust::make_zip_iterator(thrust::make_tuple(A.end(), idxlast));
select_unary_op my_unary_op;
thrust::transform(first, last, result.begin(), my_unary_op);
std::cout << "Results :" << std::endl;
thrust::copy(result.begin(), result.end(), std::ostream_iterator<int>( std::cout, " "));
std::cout << std::endl;
return 0;
}
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用向量的template_back函数
- 如何通过派生类函数更改基类中的向量
- 变量没有改变?通过向量的函数调用
- 一对向量构造函数:初始值设定项列表与显式构造
- 在c++中使用向量时,如何调用构造函数和析构函数
- std::sort()函数无法对向量的一部分进行排序
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- C++中函数的向量返回类型引发错误
- 添加存储在向量中的大整数的函数出现问题
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 具有 lambda 函数的函数向量
- 你能用参数制作函数向量吗?
- 在C++中使用成员函数向量时,有没有办法实现协变返回类型
- 在编写 lambda 函数向量时出现隔离错误
- 如何在 boost.process 间共享内存中使用复杂结构"push_back"函数向量
- 是否将std矢量重新分配到默认的构造函数向量是擦除的好方法
- 运行提升for_each中的成员函数向量
- 创建和回推函数向量
- C++,指向函数向量的指针的STL映射