How to Find the First Occurrence of an Element in a Vector?
Last Updated :
14 Feb, 2024
In C++, the vector is a dynamic array that is defined in the STL template library inside the <vector> header. In this article, we will learn how to find the first occurrence of a specific element in a vector in C++.
For Example
Input:
vector<int>v = {5, 7, 1, 2, 3, 7, 1}
Target = 1
Output:
The first occurrence of 1 is at index: 2
Find the First Occurrence of a Specific Element in a Vector
To find the first occurrence of a specific element in a std::vector, use the std::find() method that is part of the <algorithm> header and it returns an iterator that points to the first occurrence of the target element, if it is present in the vector otherwise it returns the iterator pointing to the end of the vector.
C++ Program to Find the First Occurrence of a Specific Element in a Vector
The below program demonstrates the use of the find() function to find the first occurrence of a specific element in a given vector.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v = { 5, 7, 1, 2, 3, 7, 1 };
int target = 1;
auto it = find(v.begin(), v.end(), target);
if (it != v.end()) {
cout << "The first occurrence of " << target
<< " is at index: " << it - v.begin() << endl;
}
else {
cout << "Element not found." << endl;
}
return 0;
}
|
Output
The first occurrence of 1 is at index: 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...