Standard Template Library: deque
Initialization and Assignment
What is it?
deque
(pronounced as "deck") stands for double-ended queue. It is a sequence container that is similar to a vector in terms of its functionality, but with an additional ability to efficiently add or remove elements from its beginning or end.
Syntax
std::deque<data_type> deque_name;
How to use it
To use deque
, you need to include the <deque>
header file in your C++ program. Here are some of the common operations that can be performed on a deque
:
Initialization: A deque
can be initialized in the following ways:
// Create an empty deque of integers
std::deque<int> myDeque;
// Create a deque of integers with 10 elements, initialized to 0
std::deque<int> myDeque(10);
// Create a deque of integers with 10 elements, initialized to 5
std::deque<int> myDeque(10, 5);
// Create a deque of integers with elements from an array
int myArray[] = {1, 2, 3, 4, 5};
std::deque<int> myDeque(myArray, myArray + 5);
Program code snippet example
Here is an example program that demonstrates some of the deque
operations:
#include <iostream>
#include <deque>
int main()
{
// Create a deque of integers with 10 elements, initialized to 0
std::deque<int> myDeque(10);
// Add an element to the back of the deque
myDeque.push_back(6);
// Add an element to the front of the deque
myDeque.push_front(0);
// Remove an element from the back of the deque
myDeque.pop_back();
// Remove an element from the front of the deque
myDeque.pop_front();
// Access the element at index 2
int x = myDeque.at(2);
// Access the first element
int y = myDeque.front();
// Access the last element
int z = myDeque.back();
// Iterate over the elements of the deque
for (std::deque<int>::iterator it = myDeque.begin(); it != myDeque.end(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Output:
0 0 0 0 0 0 0 0 0 6
Create two deques named dq1
and dq2
. dq1
should be initialized with 4 elements of value 10
. dq2
should be initialized with 53 5 3 54 55
.