Answers for "count in a vector C++"

C++
1

count function c++

1 #include <iostream>
2 #include <array>
3 #include <algorithm>
4
5 using namespace std;
6
7 int main(){
8 array<int, 5> nums = {1, 2, 3, 100, 2};
9 //counting number of twos
10 int numOccurrences = count(nums.begin(), nums.end(), 2);
11 cout << 2 << " appeared " << numOccurrences << " times" << endl;
12 return 0;
13 }
14
15 /*
16 2 appeared 2 times
17 */
Posted by: Guest on May-25-2020
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