赞
踩
std::multiplies
是乘法的二元函数对象。常被用于std::transform
或者std::accumulate
等的运算算子。
- template <class T> struct multiplies {
- T operator() (const T& x, const T& y) const {return x*y;}
- typedef T first_argument_type;
- typedef T second_argument_type;
- typedef T result_type;
- };
2.1两个数组的元素分别对应相乘
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <functional>
-
- int main()
- {
- std::vector<int> v1 = {10, 20, 30, 40, 50};
- std::vector<int> v2 = { 1, 2, 3, 4, 5 };
-
- std::vector<int> result(5);
- std::transform(v1.begin(), v1.end(), v2.begin(), result.begin(), std::multiplies<int>());
-
- for (int i : result) {
- std::cout << i << "\t";
- }
- std::cout << std::endl;
-
- return 0;
- }
2.2 角度与弧度的变换
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <functional>
-
- int main(int argc, const char * argv[])
- {
- std::vector<double> a = { 0, 30, 45, 60, 90, 180 };
- std::vector<double> r(a.size());
- const double pi = std::acos(-1); // since C++20 use std::numbers::pi
-
- std::transform(a.begin(), a.end(), r.begin(),
- std::bind1st(std::multiplies<double>(), pi / 180.));
- // an equivalent lambda is: [pi](double a){ return a*pi / 180.; });
-
- for (std::size_t n = 0; n < a.size(); ++n)
- std::cout << a[n] << "° = " << std::fixed << r[n]
- << " rad\n" << std::defaultfloat;
-
- return 0 ;
- }
2.3 计算阶乘
- #include <iostream> // std::cout
- #include <functional> // std::multiplies
- #include <numeric> // std::partial_sum
-
- int main(int argc, const char * argv[])
- {
- int numbers[9];
- int factorials[9];
- for (int i = 0; i < 9; i++) numbers[i] = i + 1;
- std::partial_sum(numbers, numbers + 9, factorials, std::multiplies<int>());
- for (int i = 0; i < 9; i++)
- std::cout << numbers[i] << "! is " << factorials[i] << '\n';
- return 0 ;
- }
参考:
http://www.cplusplus.com/reference/functional/multiplies/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。