Last Updated : 23 Jul, 2025
In C++, STL provides a container called deque (short for double-ended queue) that allows fast insertion and deletion at both its beginning and its end. In some scenarios, we may need to copy the contents of one deque to another. In this article, we will learn how to copy one deque to another in C++.
Example:
Input:Copying All Elements of One Deque to Another Deque in C++
deque1 = {10, 20, 30, 40, 50, 60}Output:
deque2: {10, 20, 30, 40, 50, 60}
For copying all the elements stored in one std::deque to another in C++, we can use the std::copy() function provided in the STL <algorithm> library that copies a range of elements from one container to another.
Syntax to Copy a Deque in C++copy(oldDeque.begin(), oldDeque.end(), newDeque.begin());
Here,
The below program demonstrates how we can copy one deque to another using copy() function in C++.
C++
// C++ Program to Copy One Deque to Another
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Original deque
deque<int> oldDeque = { 1, 2, 3, 4, 5 };
// destination deque
deque<int> newDeque(oldDeque.size());
// Copying Deque Using copy algorithm
copy(oldDeque.begin(), oldDeque.end(),
newDeque.begin());
// Printing original deque
cout << "Original deque:";
for (const auto& elem : oldDeque) {
cout << " " << elem;
}
cout << endl;
// Printing copied deque
cout << "Copied deque:";
for (const auto& elem : newDeque) {
cout << " " << elem;
}
cout << endl;
return 0;
}
Original deque: 1 2 3 4 5 Copied deque: 1 2 3 4 5
Time Complexity: O(N), where n is the number of elements in each deque.
Auxiliary Space: O(N)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4