当前位置:   article > 正文

C++ std::multiplies实现无视类型执行乘法_c++数组累乘

c++数组累乘

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

例子二.实现多个数字的累乘

#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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

例子三.两个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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/818453
推荐阅读
相关标签
  

闽ICP备14008679号