vector search by element
To search for an element in a C++ vector, you can follow these steps:
- Declare a vector of the desired type, for example:
std::vector<int> vec;
- Populate the vector with elements using the
push_back
method:vec.push_back(10); vec.push_back(20);
- Use the
std::find
algorithm from the<algorithm>
header to search for a specific element, for example:auto it = std::find(vec.begin(), vec.end(), 20);
- Check if the element was found by comparing the iterator to the end of the vector:
if (it != vec.end()) { / Element found / } else { / Element not found / }