std::count() returns the number of occurrences of an element in a given range. Returns the number of elements in the range [first, last) that compare equal to val.
If the val is not found at any occurrence then it returns 0(Integer value).
// Returns count of occurrences of value in // range [begin, end] int count(Iterator first, Iterator last, T &val) first, last : Input iterators to the initial and final positions of the sequence of elements. val : Value to match
Complexity It’s order of complexity O(n). Compares once each element with a particular value. Counting occurrences in an array.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 3, 2, 1, 3, 3, 5, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout <<
" Number of times 3 appears : "
<< count(arr, arr + n, 3);
return 0;
}
|
Output
Number of times 3 appears : 4
Time complexity: O(n)
Here n is size of array.
Auxiliary Space: O(1)
As constant extra space is used.
Counting occurrences in a vector.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vect{ 3, 2, 1, 3, 3, 5, 3 };
cout << "Number of times 3 appears : "
<< count(vect.begin(), vect.end(), 3);
return 0;
}
|
Output
Number of times 3 appears : 4
Time complexity: O(n)
Here n is size of vector.
Auxiliary Space: O(1)
As constant extra space is used.
Counting occurrences in a string.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "geeksforgeeks" ;
cout << "Number of times 'e' appears : "
<< count(str.begin(), str.end(), 'e' );
return 0;
}
|
Output
Number of times 'e' appears : 4
Time complexity: O(n)
Here n is the length of string.
Auxiliary Space: O(1)
As constant extra space is used.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Feb, 2023
Like Article
Save Article