|
求两个向量的内积inner_product(thrust版)
- #include <thrust/inner_product.h>
- #include <thrust/device_vector.h>
- #include <iostream>
- using namespace std;
- //求两个向量的内积inner_product(thrust版)
- int main(){
- thrust::device_vector<int> v1,v2(7); //注意这个细节
- //thrust::sequence(v1.begin(), v1.end());
- for(int i=0;i<5;i++){
- v1.push_back(i+1);
- }
- v2[0] = 4;
- v2[1] = 3;
- v2[2] = 2;
- v2[3] = 1;
- v2[4] = 0;
- v2[5] = 5;
- v2[6] = 6;
- cout << "数组初始值v1:" << endl;
- thrust::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, "\n"));
- cout << "数组初始值v2:" << endl;
- thrust::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "\n"));
- //int inner_d1_d2 = std::inner_product(d1.begin(),d1.end(),d2.begin(), 1);
- int inner_d1_d2 = thrust::inner_product(v1.begin(),v1.end(),v2.begin(), 1);
- //结果=1 + 1*4 + 2*3 + 3*2 + 4*1 + 5*0 = 21 对的
- cout<<"v1与v2的内积(1)="<<inner_d1_d2<<endl;
- //inner_d1_d2 = std::inner_product(d1.begin(),d1.end(),d2.begin(), 3,multiplies<int>(),plus<int>());
- ////应用指定的二元操作,使用第一个操作代替加而第二个操作代替乘
- inner_d1_d2 = thrust::inner_product(v1.begin(),v1.end(),v2.begin(), 3,thrust::multiplies<int>(),thrust::plus<int>());
- //结果=3 * (1+4) * (2+3) * (3+2) * (4+1) * (5+0) = 9375 对的
- cout<<"v1与v2的内积(3)="<<inner_d1_d2<<endl;
-
- return 0;
- }
- /*
- 数组初始值v1:
- 1
- 2
- 3
- 4
- 5
- 数组初始值v2:
- 4
- 3
- 2
- 1
- 0
- 5
- 6
- v1与v2的内积(1)=21
- v1与v2的内积(3)=9375
- */
复制代码
|
|