How to Reverse a Deque in C++?
Last Updated :
27 Mar, 2024
In C++ STL, we have a container called deque(short for double-ended queue) that allows fast insertion and deletion operations at both the beginning and end. In this article, we will learn how to reverse a deque in C++.
Example:
Input:
myDeque = {1, 2, 3, 4, 5};
Output:
Reversed Deque: 5 4 3 2 1
Reverse Deque in C++ STL
To reverse a std::deque in C++, we can use the std::reverse() function from the <algorithm> library that reverses the order of elements in a given range. We need to pass the beginning and end iterators of the deque to this function.
Syntax of std::reverse()
reverse(
first, last);
Here,
- first is the iterator to the beginning of the deque.
- last is the iterator to the end of the deque.
C++ Program to Reverse a Deque
The below example demonstrates how we can reverse a deque in C++.
C++
// C++ Program to demonstrate how we can reverse a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Creating a deque
deque<int> dq = { 1, 2, 3, 4, 5 };
// Printing the original deque
cout << "Original Deque: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
// Reversing the deque
reverse(dq.begin(), dq.end());
// Printing the reversed deque
cout << "Reversed Deque: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
return 0;
}
OutputOriginal Deque: 1 2 3 4 5
Reversed Deque: 5 4 3 2 1
Time Complexity: O(N), here N is the number of elements in deque.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...