A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/std-count-cpp-stl/ below:

count() in C++ STL - GeeksforGeeks

count() in C++ STL

Last Updated : 27 Nov, 2024

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:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};

    // Count the occurrence of 2
    cout << count(v.begin(), v.end(), 2);
    return 0;
}

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 Return Value Examples of count()

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

Count of Given String in Vector of Strings C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<string> v = {"Hi", "Geeks", 
                        "GeeksforGeeks", 
                        "Geeks"};

    // Count the occurrence of "Geeks"
    cout << count(v.begin(), v.end(), "Geeks");
  
    return 0;
}
Count the Frequency of Given Element in Multiset C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    multiset<int> m= {1, 1, 2, 3, 2, 2, 2, 1};
	
    // Counting the frequency of 2 
    cout << count(m.begin(), m.end(), 2);
  
    return 0;
}

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 C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {2, 3, 2, 1, 5, 4, 2};
  	int val = 7;
  
  	// Count the occurrence of 7
  	int c = count(v.begin(), v.end(), val);

    // Check if the element exists
    if (c)
      	cout << c;
    else
      	cout << val << " Not Exists";
  
    return 0;
}


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4