# (C++) count

This page is about two different counts:

• std::count: a standard algorithm to count elements in a one-dimensional container
• Count: a function to count elements in a two-dimensional container

## std::count

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

 ``` #include #include #include int main() {   std::vector 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.

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

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

### Count using a for-loop

Prefer algorithms over loops 

 ``` #include #include int Count(const std::vector >& 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& 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' 