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