To check if a specific item is present in a vector in C++, you can use the std::find
algorithm from the algorithm
header.
In this example,
vec
containing numeric elements.std::find
algorithm from the algorithm
header to search for the specified item.std::find
returns an iterator pointing to the found element. We check if the iterator is not equal to the end iterator of the vector to determine if the item is present.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int item = 3;
auto it = std::find(vec.begin(), vec.end(), item);
bool result = it != vec.end();
std::cout << std::boolalpha << result << std::endl;
return 0;
}
true
In this example,
vec
containing string elements.std::find
algorithm from the algorithm
header to search for the specified item.std::find
returns an iterator pointing to the found element. We check if the iterator is not equal to the end iterator of the vector to determine if the item is present.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> vec = {"apple", "banana", "cherry", "date"};
std::string item = "banana";
auto it = std::find(vec.begin(), vec.end(), item);
bool result = it != vec.end();
std::cout << std::boolalpha << result << std::endl;
return 0;
}
true
In this tutorial, we learned How to check if a Specific Item is present in the Vector in C++ language with well detailed examples.