Answers for "c++ count vector elements"

C++
0

c++ count vector elements

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

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

// C++11 and higher
// 3.
// #include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                               decltype(vector)::value_type(0));

// 4.
for (auto& n : vector)
    sum_of_elems += n;
Posted by: Guest on October-02-2021

Browse Popular Code Answers by Language