The sum function in C can add the elements in the container and return the result. The specific steps are as follows: Determine the container type, such as vector, list, or array. Gets an iterator pointing to the first element of the container. Use the std::accumulate function, passing in the container type, an iterator, and an initial value (usually 0). The function returns the sum of the elements in the container.
Usage of sum function in C
The sum
function in C is a general Type function that adds the elements in a container and returns the result. It accepts two parameters:
vector
, list
or array
. Usage syntax:
<code class="cpp">template<typename T, typename Iter> T sum(Iter begin, Iter end);</code>
Where:
T
is the type of container element. Iter
is the type of container iterator. Example:
Use the sum
function to sum the elements in a vector<int>
:
<code class="cpp">#include <vector> #include <numeric> // 包含 sum 函数 int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; int sum_of_numbers = std::accumulate(numbers.begin(), numbers.end(), 0); std::cout << "元素的和为:" << sum_of_numbers << std::endl; return 0; }</code>
Output:
<code>元素的和为:15</code>
Notes:
The sum
function will not sum correctly. empty
, otherwise the sum
function will throw an exception. float
and double
), the sum
function may produce small rounding errors. The above is the detailed content of How to use sum function in c++. For more information, please follow other related articles on the PHP Chinese website!