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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-26 11:16:10637browse

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

Alternative Methods for Summing Elements of a std::vector

Finding the sum of all elements in a std::vector is a common task with multiple efficient approaches. Here are several options:

Classic C 03 Techniques

For Loop:

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

Standard Algorithm:

#include <numeric>

sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);

Note: Be aware that the type of the last argument determines the result type.

Modern C Approaches (C 11 )

Automatic Type Handling:

#include <numeric>

sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                decltype(vector)::value_type(0));

std::for_each:

std::for_each(vector.begin(), vector.end(), [&](int n) {
     sum_of_elems += n;
});

Range-Based For Loop:

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

C 17 Enhancements

std::reduce:

#include <numeric>

auto result = std::reduce(v.begin(), v.end());

std::reduce handles result type inference and offers parallel execution capabilities for large collections.

The above is the detailed content of What are the Best 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