139 views
Find Member Function in Vector in C++
The C++ can use the std::find()
member function to search for an element in a vector. The std::find()
function is part of the C++ Standard Library and is included in the <algorithm>
header. It works for any type of container, including vectors.
Here’s how to use std::find()
with a vector:
C++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int target = 3; // The element to search for
// Use std::find to search for the target element in the vector
std::vector<int>::iterator it = std::find(numbers.begin(), numbers.end(), target);
if (it != numbers.end()) {
std::cout << "Element found at index: " << std::distance(numbers.begin(), it) << std::endl;
} else {
std::cout << "Element not found in the vector." << std::endl;
}
return 0;
}
In this example:
- We create a
std::vector<int>
namednumbers
and populate it with some integers. - We define a
target
variable that represents the element we want to find in the vector. - We use
std::find(numbers.begin(), numbers.end(), target)
to search for thetarget
element within the vector. Thestd::find()
function returns an iterator pointing to the found element, ornumbers.end()
if the element is not found. - We check if the iterator is equal to
numbers.end()
to determine if the element was found. If it was found, we usestd::distance()
to calculate the index of the found element.
You can use this approach to search for elements of any type in a vector or any other container supported by the C++ Standard Library.