Open In App

std::count() in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ program for count in C++ STL for
// array
#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




// C++ program for count in C++ STL for
// a vector
#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




// C++ program for the count in C++ STL
// for a string
#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.



Last Updated : 26 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads