Article directory
foreword
STL标准库中stack和queue的底层结构 :
Although elements can also be stored in stack and queue, they are not divided into the ranks of containers in STL, but are called container adapters, because stacks and queues only wrap the interfaces of other containers, STL In stack and queue, deque is used by default
1. Some basic knowledge of deque
Deque (double-ended queue): It is a double-opened "continuous" space data structure. The meaning of double-opening is: insertion and deletion operations can be performed at both ends of the head and tail, and the time complexity is O(1) . Compared with vector , the plug-in efficiency is high, and elements do not need to be moved; compared with list , the space utilization rate is relatively high.
Deque is not a real continuous space, but is spliced by a series of continuous small spaces. The actual deque is similar to a dynamic two-dimensional array
Compared to vector:
1. It greatly alleviates the problem of expansion and head plug deletion.
2. The subscript access of deque is not perfect enough. When encountering traversal, it needs to stretch a lot.
3. The iterator of deque needs to frequently check whether it has moved to a certain section the boundaries of the space, leading to inefficiencies
Compared to list:
1. It can support subscript access
. 2. The efficiency of cpu cache is good.
3. The efficiency of header insertion and deletion is the same as that of list, but the efficiency of insertion and deletion in the middle is very poor.
3Why choose deque as the underlying default container of stack and queue
Stacks and queues do not need to be traversed (so stacks and queues have no iterators), and only need to be operated on one or both ends of the fixed.
When the elements in the stack grow, deque is more efficient than vector (no need to move a lot of data when expanding); when the elements in the queue grow, deque is not only efficient, but also has high memory usage
It is very suitable for high-frequency head-plug deletion and tail-plug tail deletion
2. Implementation of stack simulation
namespace simulation {
template<class T,class Container=deque<T>>
class stack {
public:
void push(const T& x) {
_con.push_back(x);
}
void pop() {
_con.pop_back();
}
T& top() {
return _con.back();
}
size_t size() {
return _con.size();
}
bool empty() {
return _con.empty();
}
private:
Container _con;
};
}
3. Simulation implementation of queue
namespace simulationQ {
template<class T,class Container=deque<T>>
class queue {
public:
void push(const T&x) {
_con.push_back(x);
}
void pop() {
_con.pop_front();
}
T& front() {
return _con.front();
}
T& back() {
return _con.back();
}
size_t size() {
return _con.size();
}
bool empty() {
return _con.empty();
}
private:
Container _con;
};
}