|
thrust中的容器、迭代器、算法(与STL类似)案例
thrust中预定义的函数对象 如何自定义thrust的函数对象
- #include <thrust/device_vector.h>
- #include <thrust/transform.h>
- #include <thrust/sequence.h>
- #include <thrust/copy.h>
- #include <thrust/fill.h>
- #include <thrust/replace.h>
- #include <thrust/functional.h>
- #include <iostream>
- //thrust中的容器、迭代器、算法(与STL类似)案例
- //thrust中预定义的函数对象 如何自定义thrust的函数对象
- void print_thrust_vector(thrust::device_vector<int>& v){
- for(thrust::device_vector<int>::iterator it=v.begin();it!=v.end();it++){
- std::cout << "value=" << *it << std::endl;
- }
- for(int i=0; i<v.size();i++){
- //没有用迭代器 用了[]运算符取值 operator[]
- std::cout << "value_[]操作符=" << v[i] << std::endl;
- }
- }
- int main()
- {
- // allocate three device_vectors with 10 elements
- thrust::device_vector<int> X(10);
- thrust::device_vector<int> Y(10);
- thrust::device_vector<int> Z(10);
- // initialize X to 0,1,2,3, ....
- thrust::sequence(X.begin(), X.end());
- std::cout << "X的初始值:" << std::endl;
- print_thrust_vector(X);
- // compute Y = -X
- thrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>());
- std::cout << "Y的初始值:" << std::endl;
- print_thrust_vector(Y);
- // fill Z with twos
- thrust::fill(Z.begin(), Z.end(), 2);
- std::cout << "Z的初始值:" << std::endl;
- print_thrust_vector(Z);
- // compute Y = X mod 2(因为Z全是2)
- thrust::transform(X.begin(), X.end(), Z.begin(), Y.begin(), thrust::modulus<int>());
- std::cout << "Y的值(Y = X mod 2):" << std::endl;
- print_thrust_vector(Y);
- // replace all the ones in Y with tens
- thrust::replace(Y.begin(), Y.end(), 1, 10);
- std::cout << "Y的值(1替换为10):" << std::endl;
- // print Y 打印值的另外方法:
- thrust::copy(Y.begin(), Y.end(), std::ostream_iterator<int>(std::cout, "\n"));
-
- return 0;
- }
复制代码
|
|