Open In App

count() in C++ STL

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
99 Likes
Like
Report

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

This article covers the syntax, usage, and common examples of count() function in C++:

Syntax of count()

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.

Examples of count()

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

Count of Given String in Vector of Strings


Output
2

Count the Frequency of Given Element in Multiset


Output
4

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

Check Whether the Given Element Exists


Output
7 Not Exists

count() in C++ STL
Visit Course explore course icon

Explore