Find count of an element in a vector in C++
This post will discuss how to find the count of an element in a vector in C++.
1. Using std::count
The standard solution to get the count of an element in a vector is using the std::count function. It returns the total number of elements in the specified range that is equal to the target, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> values = {1, 2, 3, 2, 5, 2, 6, 7}; int target = 2; int count = std::count(values.begin(), values.end(), target); std::cout << count << std::endl; // 3 return 0; } |
2. Using std::count_if
To count the number of elements in the vector that satisfies a predicate, we can use the std::count_if standard algorithm. A typical implementation of this function would look like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 2, 5, 2, 6, 7}; int target = 2; int count = std::count_if(v.begin(), v.end(), [&target](int &i) { return i == target; }); std::cout << count << std::endl; // 3 return 0; } |
3. Using frequency map
Finally, we can create a frequency map and get the count of the specified target. This can be implemented as follows in C++.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <unordered_map> int main() { std::vector<int> values = {1, 2, 3, 2, 5, 2, 6, 7}; int target = 2; std::unordered_map<int, int> freq; for (auto &i: values) { freq[i]++; } int count = freq[target]; std::cout << count << std::endl; // 3 return 0; } |
That’s all about finding the count of an element in a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)