C++ std::accumulate

C++ 只读算法 accumulate


前言:C++只读算法有很多,今天暂且学习下accumulate。


一些算法只会读取其输入范围内的元素,而从不改变元素。比如find 和 accumulate。

头文件:#include <numeric>

std::accumulate

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

template< class InputIt, class T, class BinaryOperation >
T accumulate ( input first, last input, T init,
              Binary Operation on ) ;

accumulate函数接受三个参数,前两个指出了需要求和的元素的范围,第三个参数是和的初值。假定vec是一个整数序列,则:

//对vec中的元素求和,和的初值为0
int sum = accumulate(vec.cbegin(), vec.cend(), 0);

这条语句将sum设置为vec中元素的和,和的初值被设置为0。

accumulate的第三个参数的类型决定了函数中使用哪个加法运算符以及返回值的类型。

由于string定义了+运算符,所以我们可以通过调用accumulate来将vector中所以string元素连接起来。

std::string strSum = std::accumulate(str.begin(), str.end(), std::string(""));

对于只读取而不改变元素的算法,通常最好使用cbegin()和cend()。
但是,如果你计划使用算法返回的迭代器来改变元素的值,就需要使用begin()和end()的结果作为参数。


示例代码:

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
{
    std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::vector<std::string> str;
    str.push_back("a");
    str.push_back("b");
    int sum = std::accumulate(v.begin(), v.end(), 0);
    std::string strSum = std::accumulate(str.begin(), str.end(), std::string(""));
    int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());

    std::string s = std::accumulate(std::next(v.begin()), v.end(),
        std::to_string(v[0]), // start with first element
        [](std::string a, int b) {
        return a + '-' + std::to_string(b);
    });

    std::cout << "sum: " << sum << '\n'
        << "strSum: " << strSum << '\n'
        << "product: " << product << '\n'
        << "dash-separated string: " << s << '\n';
    return 0;
}

运行结果:

sum: 55
strSum: ab
product: 3628800
dash-separated string: 1-2-3-4-5-6-7-8-9-10

猜你喜欢

转载自blog.csdn.net/MissXy_/article/details/81104377
今日推荐