How to Remove Last Occurrence of an Element from a Vector in C++?
Last Updated :
26 Feb, 2024
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
- We will pass the reverse_iterators using vector::rbegin() and vector::rend() to the find() function.
- Then, if the element is found, it will be the last occurrence of that element due to being traversed from the end to start.
- 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++
#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< int > vec = { 5, 2, 8, 5, 8, 8 };
int element = 8;
removeLastOccurrence(vec, element);
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)
Share your thoughts in the comments
Please Login to comment...