C++ Program to Find Member Function in Vector
In C++, the find()
member function in the vector
class is used to search for a specific element in a vector. It returns an iterator pointing to the first occurrence of the element if found, or the vector::end()
iterator if the element is not present.
Syntax
The syntax for using the find()
member function in vector is:
std::vector<T>::iterator std::find (std::vector<T>::iterator first, std::vector<T>::iterator last, const T& val);
Here, first
and last
are iterators that denote the range of elements to be searched, and val
is the value to be searched.
Example
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vec{ 10, 20, 30, 40, 50 };
// Find 30 in the vector
auto it = std::find(vec.begin(), vec.end(), 30);
// If element is found, print the index
if (it != vec.end()) {
std::cout << "Element found at index: " << std::distance(vec.begin(), it);
}
else {
std::cout << "Element not found";
}
return 0;
}
Output
Element found at index: 2
Explanation
In the above code, we have defined a vector containing some elements. We then used the find()
member function to search for the element 30 in the vector. The function returns an iterator pointing to the first occurrence of the element, which is then compared with the vector::end()
iterator to check if the element was found or not. If found, the distance between the first iterator and the found iterator is printed as the index of the element in the vector.
Use
The find()
member function in vector is used to search for a specific element in the vector. It is useful when you want to check if an element is present in the vector, or to find the index of the first occurrence of the element.
Important Points
- The
find()
member function works only on sorted vectors. - The
find()
member function returns an iterator pointing to the first occurrence of the element in the vector, or thevector::end()
iterator if the element is not present. - The function takes O(N) time as it needs to search every element in the vector.
Summary
In summary, the find()
member function in vector is a powerful tool to search for a specific element in the vector. It returns an iterator to the first occurrence of the element, or the vector::end()
iterator if the element is not present. While it takes linear time to perform the search, it is still an efficient way to check if an element is present in the vector or to find its index.