c++ - 如何找到 vector 元素的乘积?

标签 c++ algorithm c++11 product stdvector

<分区>

我有以下 vector 值:[2, 3, 7]

我想输出 vector 的乘积,如 2*3*7 = 42

我为它写了一些代码,但它似乎不起作用。我是 C++ 的新手,所以我不确定如何在给定任何大小的任何数字 vector 的情况下获取 vector 中的值的乘积。

#include <bits/stdc++.h>

int main()
{
    int n;
    cin >> n;
    vector<int> vec;
    while (n--) 
    {
        int temp;
        cin >> temp;
        vec.push_back(temp);
    }
    int total = 1;
    total *= vec;
    cout << vec << endl;
    return 0;
}

最佳答案

使用 std::accumulate , 一个人可以做到

#include <numeric>    // std::accumulate
#include <functional> // std::multiplies

const auto total = std::accumulate(vec.cbegin(), vec.cend(), 1, std::multiplies<int>{});

通过包装到模板函数中,代码会更通用

template<typename Type>
auto product(const std::vector<Type>& vec, Type init)
{
    return std::accumulate(vec.cbegin(), vec.cend(), init, std::multiplies<Type>{});
}

并调用它

const auto total = product(vec, /*value to be initialized/ started with*/);

关于c++ - 如何找到 vector 元素的乘积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58489655/

相关文章:

c++ - 无法解决 opencv 代码中的 malloc 错误

c++ - 基于系统架构的 C++ 中的类大小

c++ - 为什么行>列时数组的内存占用更大

c++ - 空括号调用默认构造函数还是采用 std::initializer_list 的构造函数?

数字类型的 C++ 模板

algorithm - 我正在寻找可以接受文本字符串并将其转换为数字的算法或函数

c++ - 编程快速排序算法 Q

linq - LINQ "OrderBy"使用什么排序算法?

C++ ODB 数据库映射器:无法在关系中使用 std::weak_ptr

c++ - 涉及接口(interface)中转发引用的重载