How to Replace Second Occurrence of an Element from a Vector?
Last Updated :
26 Feb, 2024
In C++, a vector is a dynamic array that can grow and shrink in size as needed. In this article, we will learn how to replace the second occurrence of a specific element in a vector.
Example:
Input:
myVector = { 5,2,8,5,8,8}
Element: 8
Replacement: 10
Output:
myVector = { 5,2,8,5,10,8}
Replace Second Occurrence of an Element in a Vector
To replace the second occurrence of a specific element in a std::vector in C++, we can use the std::find() function to find the first occurrence of the element, and then use std::find() again to find the second occurrence. Once we have found the second occurrence, we can replace it directly in the vector using the std::vector::erase() function.
C++ Program to Replace the Second Occurrence of an Element in a Vector
The below example demonstrates the use of std::find() function to replace the second occurrence of a specific element in a vector in C++.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void replaceSecondOccurrence(vector< int >& vec, int element,
int replacement)
{
auto it = find(vec.begin(), vec.end(), element);
if (it != vec.end()) {
it = find(it + 1, vec.end(), element);
if (it != vec.end()) {
*it = replacement;
}
}
}
int main()
{
vector< int > vec = { 5, 2, 8, 5, 8, 8 };
int element = 8;
int replacement = 10;
replaceSecondOccurrence(vec, element, replacement);
cout << "Vector after replacing second occurrence of "
<< element << ": " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Output
Vector after replacing second occurrence of 8: 5 2 8 5 10 8
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...