Home >Backend Development >C++ >What are the Efficient Ways to Sum the Elements of a std::vector in C ?

What are the Efficient Ways to Sum the Elements of a std::vector in C ?

DDD
DDDOriginal
2024-12-03 16:45:13613browse

What are the Efficient Ways to Sum the Elements of a std::vector in C  ?

Efficient Methods for Summing Elements in a std::vector

In scenarios where you need to ascertain the cumulative sum of elements within a std::vector, several efficient approaches exist.

C 03 Solutions:

  1. Classic For Loop:

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

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

    Note: The final argument's type determines the initial value and result type. For floating-point inputs, use 0.0 instead of 0.

C 11 and Above Extensions:

  1. Automatic Vector Type Handling:

    #include <numeric>
    
    sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                   decltype(vector)::value_type(0));
  2. std::for_each Utilization:

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

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

C 17 and Later Additions:

  1. std::reduce with Automatic Result Type:

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

    This function's overloads enable parallel processing for extensive collections.

The above is the detailed content of What are the Efficient Ways to Sum the Elements of a std::vector in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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