http://blog.csdn.net/dreampursue/article/details/6278752
在这节中我们曾使用了这样的表达式,H.begin() 、H.end()、D.begin() + 7。begin()与end()的返回值在C++中被称为迭代器。vector的迭代器类似于数组的指针,用于指向数组的某个元素。H.begin()是指向H容器中数组第一个元素的迭代器。类似,H.end()指向H容器中的最后一个元素。
虽然说迭代器类似于指针,但它有着更丰富的作用。可以注意到在使用thrust::fill的时候我们并不需要指明这是device_vector的迭代器。这些信息包含在了D.begin()的返回值的迭代器类型中,其类型不同于H.begin()的返回值。当Thrust中的函数调用时,将根据迭代器的类型选择使用主机端还是设备端的算法实现。因为主机/设备调度是在编译时解析,所以这一过程被称为被称为静态调度。请注意,这意味着运行时没有调度进程的开销。
你可能想知道当“原始”指针作为Thrust函数的参数会如何。和STL一样,Thrust允许这种用法,它会调度主机端算法。如果传入的指针是指向设备端内存的指针,那么在调用函数之前需要用thrust::device_ptr封装。例如:
[cpp] view plaincopy
1. size_tN = 10;
2. // raw pointer to device memory
3. int raw_ptr ;
4. cudaMalloc ((void) & raw_ptr , N sizeof(int));
5. // wrap raw pointer with a device_ptr
6. thrust :: device_ptr <int> dev_ptr ( raw_ptr );
7. // use device_ptr in thrust algorithms
8. thrust :: fill ( dev_ptr , dev_ptr + N, (int) 0);
如需从 device_ptr中提取“原始”指针需要使用raw_pointer_cast,用法如下:
[cpp] view plaincopy
1. size_tN = 10;
2. // create a device_ptr
3. thrust :: device_ptr <int> dev_ptr = thrust :: device_malloc <int>(N);
4. // extract raw pointer from device_ptr
5. int* raw_ptr = thrust :: raw_pointer_cast ( dev_ptr );
迭代器另一个区别于指针的地方在于它可以遍历各种数据结构。例如,STL提供了链表容器(std::list),提供双向的(但不是随机访问)的迭代器。虽然Thrust不提供这类容器的设备端实现,但是与它们兼容。
[cpp] view plaincopy
1. # include
2. # include
3. # include
4. # include
5. intmain (void)
6. {
7. // create an STL list with 4 values
8. std :: list <int> stl_list ;
9. stl_list . push_back (10) ;
10. stl_list . push_back (20) ;
11. stl_list . push_back (30) ;
12. stl_list . push_back (40) ;
13. // initialize a device_vector with the list
14. thrust :: device_vector <int> D( stl_list . begin () , stl_list . end ());
15. // copy a device_vector into an STL vector
16. std :: vector <int> stl_vector (D. size ());
17. thrust :: copy (D. begin () , D. end () , stl_vector . begin ());
18. return0;
19. }
备注:到目前为止,我们所讨论的是十分有用但相当基本的常用迭代器。除了这些常用迭代器,Thrust也提供了counting_iterator和zip_iterator这类特殊迭代器 。虽然他们看起来与常用迭代器一样,但是特殊迭代器能够提供更令人兴奋的特性。我们将在后面的教程讨论这个问题。
原文链接: https://www.cnblogs.com/Vulkan/archive/2012/11/29/7530194.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/71066
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!