std::count() in C++ STL

std::count() returns 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.

// Returns count of occurrences of value in
// range [begin, end] 
template 
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 the particular value.

Counting occurrences in an array.

// 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;
}
Number of times 3 appears : 4

Counting occurrences in a vector.

// 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;
}
Number of times 3 appears : 4

Counting occurrences in a string.

// 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;
}
Number of times 3 appears : 4

This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.