std::function

How to Use count() in C++

Learn how to use count() in C++ through std::count, which tallies matching values in a vector, string or array, and count_if for counting by a rule.

On this page
  1. What count() does in C++
  2. Counting with a condition
  3. Counting characters in a string
  4. Counting in an array
  5. Counting in a map or set
  6. Common mistakes
  7. How fast it is
  8. Summary

What count() does in C++

In C++, count() usually refers to std::count, a function in the <algorithm> header. It counts how many elements in a range are equal to a value you give it. The range is described by two iterators: one for the first element and one for the position just past the last element.

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {1, 2, 2, 3, 2};

    auto twos = std::count(nums.begin(), nums.end(), 2);

    std::cout << twos << '\n';  // prints 3
}

nums.begin() points to the first element, and nums.end() points just past the last one, so the range covers the whole vector. The return value is the number of matches, as a signed integer.

If you are unsure how to build the vector first, see c vector initialization.

Counting with a condition

std::count_if takes a predicate instead of a value. The predicate is a function or lambda that returns true for each element you want to count:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5, 6};

    auto evens = std::count_if(nums.begin(), nums.end(), [](int x) {
        return x % 2 == 0;
    });

    std::cout << evens << '\n';  // prints 3
}

If the lambda syntax is new to you, see c lambda function.

Counting characters in a string

A std::string provides iterators just like a vector does, so std::count works on it directly:

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string word = "banana";

    auto as = std::count(word.begin(), word.end(), 'a');

    std::cout << as << '\n';  // prints 3
}

For a closer look at walking through each character, see how to iterate through a string in c.

Counting in an array

std::count also works on a C-style array when you pass std::begin and std::end:

#include <algorithm>
#include <iostream>
#include <iterator>

int main() {
    int values[] = {4, 5, 5, 7};

    auto fives = std::count(std::begin(values), std::end(values), 5);

    std::cout << fives << '\n';  // prints 2
}

std::begin and std::end come from <iterator>, which is why the example includes it.

Counting in a map or set

std::map and std::set have their own count() member function. You pass a key instead of a range. The result is 0 or 1, because their keys are unique:

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> ages = {{"Ana", 31}, {"Ben", 25}};

    std::cout << ages.count("Ana") << '\n';   // prints 1
    std::cout << ages.count("Cara") << '\n';  // prints 0
}

std::vector and std::string have no count() member, so nums.count(2) will not compile. Use std::count with the range instead.

Common mistakes

  • Missing header. std::count needs #include <algorithm>.
  • Confusing count() with size(). size() returns the number of elements, whatever their values. count() counts only the matches.
  • Signed and unsigned comparison. std::count returns a signed value, and size() returns an unsigned one. Comparing them, as in if (twos == nums.size()), can produce a sign-comparison warning. Convert one side first so both have the same sign.
  • Types without ==. std::count compares each element with ==, so a custom type needs an operator== to be counted.

How fast it is

std::count checks each element once, so the time grows with the length of the range.

Summary

  • std::count(first, last, value) counts the elements equal to value in a range.
  • std::count_if counts the elements that pass a condition.
  • The count() member of a std::map or std::set takes a key and returns 0 or 1.
  • std::vector and std::string have no count() member, so use std::count with their iterators.

The complete guide to std::function

std::function in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Header Guards in C++

A header guard stops a header from being included twice in one source file. Learn how #ifndef and #pragma once work, with examples and common mistakes.

Header Guards 4 min read