@specsoftdev live:.cid.8e17e9b93cabb607 specsoftdev@gmail.com
std::accumulate
Актуально для C++23.

#include <algorithm>
Актуально на 2024-02-12.


Define overload #1
template<class InputIterator, class T>
constexpr inline
T accumulate(InputIterator first, InputIterator last, T init);

Аккумулирует в init каждое значение из диапазона [first, last] с помощью оператора "+".
Вернёт init.
Example, possible implementation
Define overload #2
template<class InputIterator, class T, class BinaryOperation>
constexpr inline
T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

Применяет бинарный предикат binary_op к init и [first, last] переместив значение в init.
Вернёт init.
Example, possible implementation

Examples


Example 1:
#include <iostream>
#include <numeric>

int main()
{
    auto list = {1,2,3,4,5}; // сумма элементов: 15
    auto res = std::accumulate(std::begin(list), std::end(list), 5);
    std::cout << "accumulate: " << res << std::endl; // print 20
    return 0;
}

accumulate: 20

Example 2:
#include <iostream>
#include <numeric>

int main()
{
    const auto pred = [](auto init, auto el)
    {
        init += " ";
        init += std::to_string(el);
        return init;
    };
    std::string str("init string:");
    auto list = {1, 2, 3, 4, 5};
    auto res = std::accumulate(std::begin(list), std::end(list), std::move(str), pred);
    std::cout << res << std::endl;
    return 0;
}

init string: 1 2 3 4 5


See also

TODO

This page was last modified on 2024-02-12