

std::dequeDeque (usually pronounced as “deck”) is an irregular acronym: Double ended queue, in Portuguese means: Double queue, and that’s exactly what it does.
Double-ended queues are dynamically sized string containers that can be expanded or collapsed at both ends (front or back), unlike Vector which has a single row, in std::deque you can insert data either at the end, with push_back() equal in the vectors, or at the beginning: front_back() member function non-existent in vectors.
std::dequeSuppose you have a class that stores different types of data and you want to include the elements in the order they are presented to you, and first in must be first out, with which you can use push_back and then push_front:
#include <iostream>
#include <deque>
class Content {
public:
int xyz;
std::string something;
double price;
Content(int x, const std::string &s, double p)
: xyz(x), something(s), price(p) {
}
};
int main( int argc , char **argv ){
Content c1(42, "Terminal Root", 9.36);
Content c2(24, "Marcos Oliveira", 8.04);
std::deque<Content> con;
con.push_back(c1);
con.push_front(c2);
for( auto i : con) {
std::cout << i.xyz << ' ';
std::cout << i.something << ' ';
std::cout << i.price << '\n';
}
return 0;
}Output:
24 Marcos Oliveira 8.04
42 Terminal Root 9.36
If we replaced the deque with the vector we would need to reverse the order so that the result could be as expected, as we would only have the push_back:
Same code, but using
std::vector.
#include <iostream>
#include <vector>
class Content {
public:
int xyz;
std::string something;
double price;
Content(int x, const std::string &s, double p)
: xyz(x), something(s), price(p) {
}
};
int main( int argc , char **argv ){
Content c1(42, "Terminal Root", 9.36);
Content c2(24, "Marcos Oliveira", 8.04);
std::vector<Content> con;
con.push_back(c2); // We reverse the order, first we add the second so we can get the same result
con.push_back(c1);
for( auto i : con) {
std::cout << i.xyz << ' ';
std::cout << i.something << ' ';
std::cout << i.price << '\n';
}
return 0;
}push_back() and pop_back() APIs as well as vector, the deque also has the push_front() and pop_front() APIs to add and delete elements from the front.std::deque when you want to add or delete from both ends.std::vector if insertion or deletions are needed mainly at the end.deque has its biggest advantages:deque has its biggest drawbacks:std::vector, depending on what type of data request your program makes more often.Want to learn C++? Then, go to: https://terminalroot.com/tags#cpp .