std::multiplies
是乘法的二元函数对象。
常被用于
std::transform
或者
std::accumulate
等的运算算子。
例子一.实现两个数组元素的相乘
// C++ program to illustrate std::multiplies
// by multiplying the respective elements of 2 arrays
#include <iostream> // std::cout
#include <functional> // std::multiplies
#include <algorithm> // std::transform
int main()
// First array
int first[] = { 1, 2, 3, 4, 5 };
// Second array
int second[] = { 10, 20, 30, 40, 50 };
// Result array
int results[5];
// std::transform applies std::multiplies to the whole array
std::transform(first, first + 5, second, results, std::multiplies<int>());
// Printing the result array
for (int i = 0; i < 5; i++)
std::cout << results[i] << " ";
return 0;
//output:10 40 90 160 250
例子二.实现多个数字的累乘
#include <bits/stdc++.h>
int main()
// Array with elements to be multiplying
int arr[] = { 10, 20, 30 };
// size of array
int size = sizeof(arr) / sizeof(arr[0]);
// Variable with which array is to be multiplied
int num = 10;
// Variable to store result
int result;
// using std::accumulate to perform multiplication on array with num
// using std::multiplies
result = std::accumulate(arr, arr + size, num, std::multiplies<int>());
// Printing the result
std::cout << "The result of 10 * 10 * 20 * 30 is " << result;
return 0;
//output:The result of 10 * 10 * 20 * 30 is 60000
例子三.两个vector数组元素相乘
#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;
<br />#include <iostream><br />#include <string><br />#include <vector><br />#include <iterator><br />#include <algorithm><br />#include <list><br />#include <set><br />#include <cstdlib><br />#include <functional><br />#include <numeric><br />using namesp
但用普通的计算器无法完成计算,于是他请编程班的贝贝帮忙设计一个“超级计算器”,解决他所遇到的问题。贝贝是学校信息学编程小组的学生,一天,他的数学老师碰到这样一个问题:他想求。请你编一程序,帮贝贝解决这个问题。两行,分别是两个在10。
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;
accumulate(A,A+N,num,multiplies<int>)) //数组累乘 ,再和n相乘
accumulate(A, A + N, num); //数组累加 ,再和n相加
别忘了把头文件 #include<numeric>包含进来
#include<iostream>
#incl...