How to Replace Second Occurrence of an Element from a Vector?
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++
// C++ Program to illustrate how to replace the second // occurrence of a specific element in a vector. #include <algorithm> #include <iostream> #include <vector> using namespace std; void replaceSecondOccurrence(vector< int >& vec, int element, int replacement) { // Find the first occurrence auto it = find(vec.begin(), vec.end(), element); // If the element is found, find the second occurrence if (it != vec.end()) { it = find(it + 1, vec.end(), element); // If the second occurrence is found, replace it if (it != vec.end()) { *it = replacement; } } } int main() { // Vector declaration vector< int > vec = { 5, 2, 8, 5, 8, 8 }; // Element to replace and its replacement int element = 8; int replacement = 10; // Replacing the second occurrence of specific element replaceSecondOccurrence(vec, element, replacement); // Printing the vector after 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)