How to Copy a One Deque to Another in C++?
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:
deque1 = {10, 20, 30, 40, 50, 60}
Output:
deque2: {10, 20, 30, 40, 50, 60}
Copying All Elements of One Deque to Another Deque in C++
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,
- oldDeque.begin() is the iterator to the beginning of the original deque (oldDeque).
- oldDeque.end() is the iterator to the end of the original deque (oldDeque).
- newDeque.begin() is the iterator to the beginning of the destination deque(newDeque) where we have to copy the elements of the original deque.
C++ Program to Copy One Deque to Another
The below program demonstrates how we can copy one deque to another using copy() function in 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;
}
Output
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)