How to Replace All Occurrences of an Element in a Deque in C++?
In C++, we have a container called deque (short for double-ended queue) that allows the insertion and removal of elements from both ends. In this article, we will see how to replace all occurrences of a specific element in a deque in C++.
Example:
Input: myDeque = {10,20,30,40,20,60} target = 30 new_element = 100 Output: Deque after Replacing: 10 20 100 40 100 60
Replacing All Occurrences of an Element in a Deque in C++
To replace all occurrences of a specific element in a std::deque in C++, we can use the std::replace() function that replaces all occurrences of a given target value in a range with another new value.
Syntax of std::replace
replace (first, last, target, new_value);
Here,
- first: Iterator to the beginning of the range.
- last: Iterator to the end of the range.
- target: Value to be replaced.
- new_value: New value to replace the target value.
C++ Program to Replace All Occurrences of a Specific Element in a Deque
The below example demonstrates how we can use the replace() function to replace all occurrences of a specific element in a deque in C++ STL.
// C++ program to illustrate how to replace all occurrences
// of a specific element in a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Creating a deque
deque<int> myDeque = { 10, 20, 30, 40, 20, 60 };
// traget value to be removed
int target = 30;
// new value to replace target value
int new_element = 100;
// Replacing all occurrences of 30 with 100
replace(myDeque.begin(), myDeque.end(), target,
new_element);
// Printing the updated deque
cout << "Updated deque is : ";
for (int i : myDeque) {
cout << i << " ";
}
cout << endl;
return 0;
}
Output
Updated deque is : 10 20 100 40 20 60
Time Complexity: O(n), here n is the number of elements in the deque.
Auxiliary Space: O(1)
Contact Us