Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) count

 

This page is about two different counts:

 

 

 

 

 

std::count

 

std::count is an STL algorithm for counting elements in a container. For conditional counting use std::count_if.

 

#include <algorithm>
#include <cassert>
#include <vector>

int main()
{
  std::vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(2);
  v.push_back(3);
  v.push_back(3);
  v.push_back(3);

  assert(std::count(v.begin(),v.end(),1)==1);
  assert(std::count(v.begin(),v.end(),2)==2);
  assert(std::count(v.begin(),v.end(),3)==3);
}

 

 

 

 

 

Count

 

Count is a function to count elements in a two-dimensional container.

 

 

 

 

 

 

C++11STL Count using a C++11 lambda expression

 

#include <algorithm>
#include <cassert>
#include <numeric>
#include <vector>

int Count(const std::vector<std::vector<int> >& v, const int value)
{
  return std::accumulate(v.begin(),v.end(),0,
    [value](int& sum, const std::vector<int>& w)
    {
      return sum + std::count(w.begin(),w.end(),value);
    }
  );
}

 

 

 

 

 

C++98 Count using a for-loop

 

Prefer algorithms over loops [1][2]

 

#include <cassert>
#include <vector>

int Count(const std::vector<std::vector<int> >& v, const int value)
{
  int cnt = 0;
  const std::size_t maxi = v.size();
  for (std::size_t i = 0; i!=maxi; ++i)
  {
    const std::vector<int>& w = v[i];
    const std::size_t maxj = w.size();
    for (std::size_t j = 0; j!=maxj; ++j)
    {
      if (w[j] == value) ++cnt;
    }
  }
  return cnt;
}

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms over loops'
  2. Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict