Home > Backend Development > C++ > body text

How to find sum in c++

下次还敢
Release: 2024-04-28 18:06:17
Original
686 people have browsed it

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 find sum in c++

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>
Copy after login
  • 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>
Copy after login

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>
Copy after login

Notes

  • For very large or very small sizes that may produce overflow numbers, consider using long long or other large integer types.
  • For an empty container or range, the sum function returns the initial value (usually 0).

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!

Related labels:
c++
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template