Home > Backend Development > C++ > How to express sum in c++

How to express sum in c++

下次还敢
Release: 2024-05-01 10:24:15
Original
703 people have browsed it

Sums in C can be expressed in the following ways: a normal loop, std::accumulate, a ranged for loop, and std::reduce (C 20 and later). The choice depends on the amount of data, the need to operate on the elements, and the C version.

How to express sum in c++

Representation of summation in C

In C, summation can be expressed in the following ways:

1. Ordinary loop

<code class="cpp">int sum = 0;
for (int i = 0; i < n; i++) {
    sum += arr[i];
}</code>
Copy after login

2. std::accumulate

<code class="cpp">int sum = std::accumulate(std::begin(arr), std::end(arr), 0);</code>
Copy after login

3. Range for loop

<code class="cpp">int sum = 0;
for (int num : arr) {
    sum += num;
}</code>
Copy after login

4. std::reduce (C 20 and above)

<code class="cpp">int sum = std::reduce(std::begin(arr), std::end(arr), 0, std::plus<int>{});</code>
Copy after login

Selection scheme

Which summation representation to choose depends on the specific situation. Generally speaking:

  • Normal loop is suitable for small amounts of data or when some operations need to be performed on elements.
  • std::accumulate Provides concise syntax and is suitable for large data volumes.
  • Scope for loop Provides a short syntax that works in C 11 and later.
  • std::reduce is the more general summation function available in C 20 and later.

The above is the detailed content of How to express 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template