How to Find the Second Occurrence of an Element in Vector in C++?
Last Updated :
08 Feb, 2024
In C++, vector containers store the data in a contiguous memory location like arrays and also can resize themselves to store more elements. In this article, we will learn how to find the second occurrence of a specific element in a vector in C++.
Example
Input:
myVector = {20, 30, 10, 50, 10, 80, 10}
Output:
Second occurrence of element 10 is found at index 4
Find the Second Occurrence of an Element in a Vector in C++
The C++ Standard Template Library(STL) provides a method std::find() which returns an iterator to the first occurrence of the specified element in the given range of values. We will use the find() method to find the second occurrence of our required element in the vector by simply running it two times.
Syntax of find()
find(first , last, value);
- first: iterator to the initial position of the range.
- last: iterator to position just after the final position of the range.
- value: value to be searched.
C++ Program to Find the First Occurrence of an Element in Vector
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 20, 30, 10, 50, 10, 80, 10 };
int elementToFind = 10;
auto it = find(vec.begin(), vec.end(), elementToFind);
if (it != vec.end()) {
it = find(it + 1, vec.end(), elementToFind);
if (it != vec.end()) {
cout << "Second occurrence of element "
<< elementToFind
<< " found at index: " << it - vec.begin()
<< endl;
}
else {
cout << "Second occurrence of element not found"
<< endl;
}
}
else {
cout << "Element not found" << endl;
}
return 0;
}
|
Output
Second occurrence of element 10 found at index: 4
Time Complexity: O(N) where N is the number of elements in the vector
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...