Home > Backend Development > C++ > How Can I Efficiently Sum the Elements of a std::vector in C ?

How Can I Efficiently Sum the Elements of a std::vector in C ?

Susan Sarandon
Release: 2024-12-01 01:52:10
Original
651 people have browsed it

How Can I Efficiently Sum the Elements of a std::vector in C  ?

Summation Techniques for Elements in a std::vector

Finding the sum of elements in a std::vector is a common operation. Here are various approaches:

C 03

  • Classic For Loop:

    int sum_of_elems = 0;
    for (std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
      sum_of_elems += *it;
    Copy after login
  • Standard Algorithm:

    #include <numeric>
    sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
    Copy after login

C 11 and Above

  • Automatic Type Tracking:

    #include <numeric>
    sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                  decltype(vector)::value_type(0));
    Copy after login
  • std::for_each:

    std::for_each(vector.begin(), vector.end(), [&] (int n) {
      sum_of_elems += n;
    });
    Copy after login
  • Range-Based For Loop:

    for (auto& n : vector)
      sum_of_elems += n;
    Copy after login

C 17 and Above

  • std::reduce:

    #include <numeric>
    auto result = std::reduce(v.begin(), v.end());
    Copy after login

This function infers the result type based on the vector's element type, allowing for automatic handling of different numeric types.

The above is the detailed content of How Can I Efficiently Sum the Elements of a std::vector in C ?. For more information, please follow other related articles on the PHP Chinese website!

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