Open In App

How to Remove Last 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 same as dynamic arrays with the ability to resize automatically when an element is inserted or deleted, with their storage being handled automatically by the container. In this article, we will learn how to remove the last occurrence of a specific element in a vector.

Input:
myVector = { 5,2,8,5,8,8}
Element: 8

Output:
myVector = { 5,2,8,5,8}

Remove Last Occurrence of an Element from Vector in C++

To remove the last occurrence of an element in a std::vector in C++, we can use the std::find() function in combination with std::vector::erase().

The std::find() function returns an iterator pointing to the first occurrence of the element if it is found. If the element is not found, it returns an iterator pointing to the end of the vector. The std::vector::erase() function removes the element pointed to by the iterator.

Approach

  1. We will pass the reverse_iterators using vector::rbegin() and vector::rend() to the find() function.
  2. Then, if the element is found, it will be the last occurrence of that element due to being traversed from the end to start.
  3. We will then pass this iterator to the std::vector::erase() function which will remove it from the vector.

C++ Program to Remove Last Occurrence of an Element from Vector in C++

C++




// C++ Program to remove all occurrences of a specific
// element from a vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
void removeLastOccurrence(vector<int>& vec, int element)
{
    auto it = find(vec.rbegin(), vec.rend(), element);
    if (it != vec.rend())
        vec.erase((it + 1).base());
}
  
int main()
{
    // Vector declaration
    vector<int> vec = { 5, 2, 8, 5, 8, 8 };
  
    // Element to remove
    int element = 8;
  
    // Removing the last occurrence of specific element
    removeLastOccurrence(vec, element);
  
    // Printing the vector after removal
    cout << "Vector after removing last occurrence of "
         << element << ": ";
    for (int i : vec) {
        cout << i << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Vector after removing last occurrence of 8: 5 2 8 5 8 

Time Complexity: O(n),
Space Complexity: O(1)



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

Similar Reads