In C++, deque (short for double-ended queue) allows fast insertions and deletions at both its beginning and its end. In this article, we will learn how to replace a specific element in a deque in C++.
Example:
Input: myDeque: {1, 2, 3, 4, 5, 3, 7} Output: // Replaced element 3 with 10 Updated Deque: 1 2 10 4 5 10 7
Replace an Element in a Deque in C++
To replace a specific element in a deque in C++, we can use the std::replace() method provided by the STL library. The replace method will replace all the occurrences of the specific element within the given range.
Syntax of std::replace()
replace(first, last, int target, int substitute)
where,
- first and last are iterators denoting the range of dequeue elements.
- target is the element you want to replace.
- substitute is the element you want to replace target element with.
C++ Program to Replace a Specific Element in a Deque
The below program demonstrates how we can replace a specific element in a deque in C++:
// C++ Program to illustrate how to replace a specific
// element in a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Initialize a deque
deque<int> dq = { 1, 2, 3, 4, 5, 3, 7 };
// Declare the target element
int target = 3;
// Declare the substitute element
int substitute = 10;
// Print the original deque
cout << "Original Deque: ";
for (int x : dq) {
cout << x << " ";
}
cout << endl;
// Replace the specific element in the deque
replace(dq.begin(), dq.end(), target, substitute);
// Print the updated deque
cout << "Updated Deque: ";
for (int x : dq) {
cout << x << " ";
}
return 0;
}
Output
Original Deque: 1 2 3 4 5 3 7 Updated Deque: 1 2 10 4 5 10 7
Time Complexity: O(N) where N is the size of deque
Auxiliary Space: O(1)