# std::count() in C++ STL

• Difficulty Level : Easy
• Last Updated : 22 Sep, 2019

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]
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 ``using` `namespace` `std;`` ` `int` `main()``{``    ``int` `arr[] = { 3, 2, 1, 3, 3, 5, 3 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``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 ``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 ``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 'e' 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.

My Personal Notes arrow_drop_up