Several ways to sum in C include: Built-in function std::accumulate(): Calculates the sum of a series of values. Built-in function sum(): Short for accumulate(), takes a container as input. Container method std::vector::accumulate(): Specially used for std::vector containers. Container method std::vector::sum(): Returns the sum of all elements in the container.
How to sum in C
C provides a variety of built-in functions and container methods to calculate arrays and vectors Or the sum of the elements in the list.
Built-in function
accumulate()
: Used to calculate the sum of a series of values. It accepts an iterator range and an optional initial value, and returns the sum. <code class="cpp">#include <numeric> #include <iostream> int main() { int arr[] = {1, 3, 5, 7, 9}; int sum = std::accumulate(arr, arr + 5, 0); std::cout << "总和为:" << sum << std::endl; return 0; }</code>
sum()
: This is the abbreviated version of accumulate()
which takes a container as input and returns the sum. <code class="cpp">#include <vector> int main() { std::vector<int> vec = {1, 3, 5, 7, 9}; int sum = std::sum(vec); std::cout << "总和为:" << sum << std::endl; return 0; }</code>
Container methods
std::vector::accumulate()
: Similar to std: :accumulate()
, but designed specifically for std::vector
containers. std::vector::sum()
: Returns the sum of all elements in the container, similar to std::sum()
. Example
<code class="cpp">#include <vector> int main() { std::vector<int> vec = {1, 3, 5, 7, 9}; int sum = std::accumulate(vec.begin(), vec.end(), 0); std::cout << "总和为:" << sum << std::endl; return 0; }</code>
Notes
long long
or other large integer types. The above is the detailed content of How to find sum in c++. For more information, please follow other related articles on the PHP Chinese website!