MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / average

Function average

Exercises/NoModules/Chapter 20/Soln20_05/Soln20_05.cpp:12–18  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10// which only works for random-access iterators)
11template <typename T, typename IterType>
12std::optional<T> average(IterType begin, IterType end)
13{
14 const auto count{ std::distance(begin, end) };
15 const auto sum{ std::accumulate(begin, end, T{}) };
16
17 return count ? std::optional<T>{ sum / count } : std::nullopt;
18}
19
20// Solution 2: accumulate a pair<> that counts both the number of elements and the sum
21//template <typename T, typename IterType>

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected