VOOZH about

URL: https://www.geeksforgeeks.org/cpp/std-count-cpp-stl/

⇱ count() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

count() in C++ STL

Last Updated : 19 Jan, 2026

In C++, the count() is a built-in function used to find the number of occurrences of an element in the given range. This range can be any STL container or an array. In this article, we will learn about the count() function in C++.

Let’s take a quick look at a simple example that uses count() method:


Output
3

Syntax

The count() function is defined inside the <algorithm> header file.

count(first, last, val);

Parameters

  • first: Iterator to the first element of the range.
  • last: Iterator to the element just after the last element of the range.
  • val: Value to be counted.

Return Value

  • If the value found, it returns the number of its occurrences.
  • Otherwise, it returns 0.

The following examples demonstrates the use of count() function for different purposes:

Example 1: Count of Given String in Vector of Strings


Output
2

Explantion: count(v.begin(), v.end(), "Geeks") counts and prints the number of times "Geeks" appears in the vector v.

Example 2: Count the Frequency of Given Element in Multiset


Output
4

Explanation: count(m.begin(), m.end(), 2) counts and prints how many times the value 2 appears in the multiset m.

Note: Unique value containers such as set, maps, etc. can only return either 1 or 0 from the count function.

Example 3: Check Whether the Given Element Exists


Output
7 Not Exists

Explanation:It counts how many times the value 7 appears in the vector v and prints the count if present, otherwise prints "7 Not Exists".

Comment