当前位置:   article > 正文

C++的std::multiplies

std::multiplies

一、介绍

std::multiplies是乘法的二元函数对象。常被用于std::transform或者std::accumulate等的运算算子。

  1. template <class T> struct multiplies {
  2. T operator() (const T& x, const T& y) const {return x*y;}
  3. typedef T first_argument_type;
  4. typedef T second_argument_type;
  5. typedef T result_type;
  6. };

二、实例

2.1两个数组的元素分别对应相乘

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <functional>
  5. int main()
  6. {
  7. std::vector<int> v1 = {10, 20, 30, 40, 50};
  8. std::vector<int> v2 = { 1, 2, 3, 4, 5 };
  9. std::vector<int> result(5);
  10. std::transform(v1.begin(), v1.end(), v2.begin(), result.begin(), std::multiplies<int>());
  11. for (int i : result) {
  12. std::cout << i << "\t";
  13. }
  14. std::cout << std::endl;
  15. return 0;
  16. }

 

2.2 角度与弧度的变换

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <functional>
  5. int main(int argc, const char * argv[])
  6. {
  7. std::vector<double> a = { 0, 30, 45, 60, 90, 180 };
  8. std::vector<double> r(a.size());
  9. const double pi = std::acos(-1); // since C++20 use std::numbers::pi
  10. std::transform(a.begin(), a.end(), r.begin(),
  11. std::bind1st(std::multiplies<double>(), pi / 180.));
  12. // an equivalent lambda is: [pi](double a){ return a*pi / 180.; });
  13. for (std::size_t n = 0; n < a.size(); ++n)
  14. std::cout << a[n] << "° = " << std::fixed << r[n]
  15. << " rad\n" << std::defaultfloat;
  16. return 0 ;
  17. }

2.3 计算阶乘

  1. #include <iostream> // std::cout
  2. #include <functional> // std::multiplies
  3. #include <numeric> // std::partial_sum
  4. int main(int argc, const char * argv[])
  5. {
  6. int numbers[9];
  7. int factorials[9];
  8. for (int i = 0; i < 9; i++) numbers[i] = i + 1;
  9. std::partial_sum(numbers, numbers + 9, factorials, std::multiplies<int>());
  10. for (int i = 0; i < 9; i++)
  11. std::cout << numbers[i] << "! is " << factorials[i] << '\n';
  12. return 0 ;
  13. }

参考:

http://www.cplusplus.com/reference/functional/multiplies/

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/818502
推荐阅读
相关标签
  

闽ICP备14008679号