C++ Vector Search: Find Elements Efficiently
To find a specific element using a vector, you can use the std::find function. The specific steps are as follows:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int target = 3;
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout << "Element found at index: " << std::distance(vec.begin(), it) << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
In the code above, we defined a vector and checked if it contains an element with a value of 3. By using the std::find function, we can search for a specified element in the vector and return its iterator. If the element is found, the index position of the element is outputted, if not, “Element not found” is outputted.