std::multiplies是乘法的二元函数对象。
常被用于std::transform或者std::accumulate等的运算算子。
例子一.实现两个数组元素的相乘
// C++ program to illustrate std::multiplies
// by multiplying the respective elements of 2 arrays
// std::cout
// std::multiplies
// 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
例子二.实现多个数字的累乘
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数组元素相乘
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;
}