C++ std::multiplies实现无视类型执行乘法

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值