To count the number of occurrences of a specific item in a vector in C++, you can use the std::count
function from the <algorithm>
library.
In this example,
<iostream>
for input and output and <vector>
for using the vector container, and <algorithm>
for the std::count
function.std
namespace to simplify code.vec
with a set of numerical values using the std::vector<int>
container.item
that holds the value we want to count in the vector.std::count
function to count the occurrences of item
in vec
. The function takes two iterators to specify the range of elements to examine and the value to count.std::cout
stream.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 2, 2, 4, 5, 2};
int item = 2;
int count = std::count(vec.begin(), vec.end(), item);
std::cout << count << std::endl;
return 0;
}
4
In this example,
<iostream>
for input and output, <vector>
for using the vector container, and <algorithm>
for the std::count
function.std
namespace to simplify code.char_vec
with a set of string values using the std::vector<std::string>
container.str_item
that holds the string we want to count in the vector.std::count
function to count the occurrences of str_item
in char_vec
. The function takes two iterators to specify the range of elements to examine and the value to count.std::cout
stream.#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main() {
std::vector<std::string> char_vec = {"apple", "banana", "apple", "cherry", "banana", "apple"};
std::string str_item = "apple";
int count = std::count(char_vec.begin(), char_vec.end(), str_item);
std::cout << count << std::endl;
return 0;
}
3
In this example,
<iostream>
for input and output and <vector>
for using the vector container, and <algorithm>
for the std::count
function.std
namespace to simplify code.bool_vec
with a set of boolean values using the std::vector<bool>
container.bool_item
that holds the boolean value we want to count in the vector.std::count
function to count the occurrences of bool_item
in bool_vec
. The function takes two iterators to specify the range of elements to examine and the value to count.std::cout
stream.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<bool> bool_vec = {true, false, true, true, false, true, false};
bool bool_item = true;
int count = std::count(bool_vec.begin(), bool_vec.end(), bool_item);
std::cout << count << std::endl;
return 0;
}
4
In this tutorial, we learned How to count the Number of Occurrences of Specific Item in the Vector in C++ language with well detailed examples.