DQue
DQue
#include <deque>
Once we import this file, we can create a deque using the following syntax:
deque<type> dq;
Here, type indicates the data type we want to store in the deque. For
example,
Initialize a Deque
We can initialize a C++ deque in the following ways:
// function prototype
void display_deque(deque<int>);
int main() {
// uniform initialization
deque<int> deque1 {1, 2, 3, 4, 5};
return 0;
}
Run Code
Output
deque1 = 1, 2, 3, 4, 5,
Then, we have displayed the deque contents using a ranged for loop.
int main() {
return 0;
}
Run Code
Output
Initial Deque: 2, 3,
Final Deque: 1, 2, 3, 4,
// nums = {2, 3, 4}
nums.push_back(4);
Note: We can also use the insert() and emplace() methods to add elements
to the deque.
#include <iostream>
#include <deque>
using namespace std;
int main() {
return 0;
}
Run Code
Output
Front element: 1
Back element: 3
Element at index 1: 2
Element at index 0: 1
int main() {
return 0;
}
Run Code
Output
Initial Deque: 1, 2,
Updated Deque: 3, 4,
In the above example, the initial contents of the nums deque are {1, 2} .
Then, we have used the at() method to change the elements at the
specified indexes:
nums.at(0) = 2; - changes the value at index 0 changes to 3
nums.at(1) = 4; - changes the value at index 1 to 4
#include <iostream>
#include <deque>
using namespace std;
int main() {
return 0;
}
Output
Initial Deque: 1, 2, 3,
Deque after pop_back(): 1, 2,
Deque after pop_front(): 2,
In the above example, we have initialized an integer deque named nums with
the elements {1, 2, 3} .
deque<type>::iterator itertaor_name;
For example,
int main() {
return 0;
}
Run Code
Output
nums[0] = 1
nums[1] = 2
nums[2] = 3
deque<int>::iterator dq_iter;
Then, we have used the dq_iter iterator to point to the following elements:
1. The First Element
dq_iter = nums.begin();
Here, the begin() method returns an iterator that points to the first element.
2. Element at Index 1
dq_iter = nums.begin() + 1;
The code begin() + 1 returns an iterator that points to the element at index
1.
dq_iter = nums.end() - 1;
This is because the end() method iterator points to the iterator past the last
element. So, in order to get the final element, we are subtracting 1.
4. Get the Element Value
After using dq_iter to point to a certain element, we use the indirection
operator * to get the value of that element:
// returns 1
int first_element = *dq_iter;