@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