Determining the Sum of Elements in a C Vector
In C , finding the sum of elements in a std::vector requires a loop or standard algorithm to iterate over and accumulate the values. The choice of method depends on the version of C used, and each approach offers its own advantages.
C 03
Classic for loop: Using a traditional for loop to iterate through the elements and increment a running sum variable.
int sum_of_elems = 0; for (auto it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it;
accumulate algorithm: This algorithm provided by the
#include <numeric> int sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
C 11 and Higher
std::accumulate with auto-typing: The same std::accumulate algorithm can be used with a slight modification to automatically deduce the return type based on the vector's element type.
#include <numeric> decltype(vector)::value_type sum_of_elems = std::accumulate(vector.begin(), vector.end(), decltype(vector)::value_type(0));
std::for_each loop: This loop syntax applies a lambda function to each element of the vector, updating a sum variable within its scope.
std::for_each(vector.begin(), vector.end(), [&](int n) { sum_of_elems += n; });
Range-based for loop: This syntactic sugar for loops iterates over the elements directly without a separate iterator object.
for (auto& n : vector) sum_of_elems += n;
C 17 and Later
std::reduce algorithm: This algorithm combines the elements of a collection into a single result using a specific binary operator, in this case addition. It also automatically infers the result type.
#include <numeric> auto result = std::reduce(v.begin(), v.end());
The above is the detailed content of How Can I Efficiently Sum the Elements of a C Vector?. For more information, please follow other related articles on the PHP Chinese website!