Open In App

How to Find the Second Occurrence of an Element in Vector in C++?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate finding the index of the
// second occurrence of a specific element in a vector
#include <algorithm>
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> vec = { 20, 30, 10, 50, 10, 80, 10 };
  
    // declare the element you want to find
    int elementToFind = 10;
  
    // call the find function to search for the first
    // occurrence of the element and store the result in the
    // iterator
    auto it = find(vec.begin(), vec.end(), elementToFind);
  
    // If the first occurrence of the element is found
    if (it != vec.end()) {
        // call the find function again to search for the
        // second occurrence of the element
        it = find(it + 1, vec.end(), elementToFind);
  
        // If the second occurrence of the element is found,
        // print its index
        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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads