在 C++ 中计算数组的总和

本文将介绍几种如何在 C++ 中计算数组元素之和的方法。

使用 std::accumulate 函数来计算 C++ 中的数组元素之和

std::accumulate 是 STL 库中头文件 <numeric> 下包含的数字函数的一部分。std::accumulate 是一个通用函数,适用于给定范围内的元素,该范围由相应迭代器表示的前两个参数指定。第三个参数用于传递总和的初始值,该初始值可以是对象的文字值。在这种情况下,我们演示了一个动态整数数组,该数组存储在 std::vector 容器中。注意,std::accumulate 可以选择采用二进制函数对象类型的第四个参数来代替加法运算。在下一个示例代码中对 std::accumulate 的第二次调用演示了这种情况,唯一的区别是乘法被用作二进制运算。

#include <iostream>#include <vector>#include <numeric>using std::cout; using std::cin;
using std::endl; using std::vector;
using std::accumulate;
template<typename T>
void printVector(vector<T> &vec)
{
    for (const auto &item : vec) {
        cout << item << ", ";
    }
    cout << endl;
}
int main() {
    vector<int> arr1 = { 1, 12, 13, 10, 11 };
    printVector(arr1);
    int arr1_sum = accumulate(arr1.begin(), arr1.end(), 0);
    cout << "sum of arr1 = " << arr1_sum << endl;
    int arr1_product = accumulate(arr1.begin(), arr1.end(),1, std::multiplies<>());
    cout << "product of arr1 = " << arr1_product << endl;
    return EXIT_SUCCESS;
}

输出:

1, 12, 13, 10, 11,
sum of arr1 = 47
product of arr1 = 17160

使用 std::partial_sum 函数来计算 C++ 中子数组的部分和

同一头文件提供的另一个有用的数字函数是 std::partial_sum,该函数将给定范围内的子范围相加。该函数提供的接口与上一个接口相似,不同之处在于,第三个参数应该是将存储计算所得数字的范围的起始迭代器。在这种情况下,我们用相加的结果覆盖现有的矢量元素。注意,也可以用 std::partial_sum 指定自定义二进制操作,以更改默认选项-加法。

#include <iostream>#include <vector>#include <numeric>using std::cout; using std::cin;
using std::endl; using std::vector;
template<typename T>
void printVector(vector<T> &vec)
{
    for (const auto &item : vec) {
        cout << item << ", ";
    }
    cout << endl;
}
int main() {
    vector<int> arr1 = { 1, 12, 13, 10, 11 };
    printVector(arr1);
    std::partial_sum(arr1.begin(), arr1.end(), arr1.begin());
    printVector(arr1);
    std::partial_sum(arr1.begin(), arr1.end(), arr1.begin(), std::multiplies());
    printVector(arr1);
    return EXIT_SUCCESS;
}

输出:

1, 13, 26, 36, 47,
1, 13, 338, 12168, 571896,

或者,这些功能也可用于在给定范围内的元素之间进行按位运算。例如,以下代码片段对 vector 元素进行 XOR,并将结果值存储在相同范围内。

#include <iostream>#include <vector>#include <numeric>using std::cout; using std::cin;
using std::endl; using std::vector;
template<typename T>
void printVector(vector<T> &vec)
{
    for (const auto &item : vec) {
        cout << item << ", ";
    }
    cout << endl;
}
int main() {
    vector<int> arr1 = { 1, 12, 13, 10, 11 };
    printVector(arr1);
    std::partial_sum(arr1.begin(), arr1.end(), arr1.begin(), std::bit_xor());
    printVector(arr1);
    return EXIT_SUCCESS;
}

输出:

1, 13, 0, 10, 1,