东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 1418|回复: 1
打印 上一主题 下一主题

[C/C++] thrust中的容器、迭代器、算法(与STL类似)案例

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14451
QQ
跳转到指定楼层
楼主
发表于 2021-7-6 10:00:46 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式



thrust中的容器、迭代器、算法(与STL类似)案例


thrust中预定义的函数对象 如何自定义thrust的函数对象


  1. #include <thrust/device_vector.h>
  2. #include <thrust/transform.h>
  3. #include <thrust/sequence.h>
  4. #include <thrust/copy.h>
  5. #include <thrust/fill.h>
  6. #include <thrust/replace.h>
  7. #include <thrust/functional.h>
  8. #include <iostream>

  9. //thrust中的容器、迭代器、算法(与STL类似)案例
  10. //thrust中预定义的函数对象 如何自定义thrust的函数对象

  11. void print_thrust_vector(thrust::device_vector<int>& v){
  12.     for(thrust::device_vector<int>::iterator it=v.begin();it!=v.end();it++){
  13.         std::cout << "value=" << *it << std::endl;
  14.     }
  15.     for(int i=0; i<v.size();i++){
  16.         //没有用迭代器 用了[]运算符取值  operator[]
  17.         std::cout << "value_[]操作符=" << v[i] << std::endl;
  18.     }
  19. }

  20. int main()
  21. {
  22.   // allocate three device_vectors with 10 elements
  23.   thrust::device_vector<int> X(10);
  24.   thrust::device_vector<int> Y(10);
  25.   thrust::device_vector<int> Z(10);

  26.   // initialize X to 0,1,2,3, ....
  27.   thrust::sequence(X.begin(), X.end());
  28.   std::cout << "X的初始值:" << std::endl;
  29.   print_thrust_vector(X);

  30.   // compute Y = -X   
  31.   thrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>());
  32.   std::cout << "Y的初始值:" << std::endl;
  33.   print_thrust_vector(Y);

  34.   // fill Z with twos
  35.   thrust::fill(Z.begin(), Z.end(), 2);
  36.   std::cout << "Z的初始值:" << std::endl;
  37.   print_thrust_vector(Z);



  38.   // compute Y = X mod 2(因为Z全是2)
  39.   thrust::transform(X.begin(), X.end(), Z.begin(), Y.begin(), thrust::modulus<int>());

  40.   std::cout << "Y的值(Y = X mod 2):" << std::endl;
  41.   print_thrust_vector(Y);


  42.   // replace all the ones in Y with tens
  43.   thrust::replace(Y.begin(), Y.end(), 1, 10);
  44.   std::cout << "Y的值(1替换为10):" << std::endl;
  45.   // print Y 打印值的另外方法:
  46.   thrust::copy(Y.begin(), Y.end(), std::ostream_iterator<int>(std::cout, "\n"));
  47.    
  48.   return 0;   
  49. }
复制代码


让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

0

主题

98

帖子

200

积分

中级会员

Rank: 3Rank: 3

积分
200
沙发
发表于 2021-11-23 19:36:57 | 只看该作者
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-6-18 21:47 , Processed in 0.173248 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表