Open In App

How to Remove Second Occurrence of an Element from a Vector in C++?

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

In C++, vectors are the dynamic arrays that store the data in the contiguous memory location. It can also contain multiple copies of the same element. In this article, we will learn how to remove the second occurrence of an element from a vector in C++.

Example:

Input:
myVector = {1, 2, 3, 4, 2, 5, 2};
Key = 2

Output:
Elements before removing target is: {1, 2, 3, 4, 2, 5, 2};
Elements after removing target is: {1, 2, 3, 4, 5, 2};

Remove Second Occurrence of an Element from a Vector in C++

To remove the second occurrence of an element from a vector in C++, we can use the combination of std::find() and std::vector::erase() functions.

We can use the std::find() function to find the second occurrence and then use the std::vector::erase() function to remove the second occurence.

C++ Program to Remove Second Occurrence of an Element from a Vector

C++




#include <algorithm>
#include <iostream>
#include <vector>
  
using namespace std;
  
// Function to remove the second occurrence of an element
// from a vector
void removeSecondOccurrence(vector<int>& vec, int element)
{
    // Find the first occurrence of the element
    auto it = find(vec.begin(), vec.end(), element);
  
    // If the element is found, find the second occurrence
    if (it != vec.end()) {
        // Advance the iterator to the next element to find
        // the second occurrence
        it = find(it + 1, vec.end(), element);
  
        // If the second occurrence is found, erase it
        if (it != vec.end()) {
            vec.erase(it);
        }
    }
}
  
int main()
{
    // Create a vector with some elements
    vector<int> vec = { 1, 2, 3, 2, 4, 2, 5 };
  
    // Print the original vector
    cout << "Original vector: ";
    for (int i : vec) {
        cout << i << " ";
    }
    cout << endl;
  
    // Call the removeSecondOccurrence function to remove
    // the second occurrence of 2
    removeSecondOccurrence(vec, 2);
  
    // Print the modified vector after removing the second
    // occurrence of 2
    cout << "After removing second occurrence of 2: ";
    for (int i : vec) {
        cout << i << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Original vector: 1 2 3 2 4 2 5 
After removing second occurrence of 2: 1 2 3 4 2 5 

Time Complexity: O(N)
Space Complexity: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads