Notes from C++ Primer
- stack and queue: based on deque
- priority_queue: based on vector
Standard library provides three kinds of sequential adaptors: queue, priority_queue and stack. When we use adaptor, we must include the relevant head files:
#include <stack>
#include <queue> // both queue and priority_queue adaptors
We can use two ways to initialize the adaptor: default constructor or a constructor with one container parameter:
deque<int> deq;
stack<int> stk(deq); // copies elements from deq into stk
Also we can override the underlying container type by passing a sequential container type:
// empty stack implemented on top of vector
stack<string, vector<string> > str_stk;
// str_stk2 is implemented on top of vector and holds a copy of svec
stack<string, vector<string> > str_stk2(svec);
There're constraints on which containers can be used for a given adaptor.
- stack: any sequential container: vector, list, deque
- queue: the underlying container must support push_front, so only based on: list
- priority_queue: the underlying container should support random access, so based on: vecotr or deque
Stack Adaptor Operation
- s.empty() if the stack is empty, return true
- s.size() return the size of elements in the stack
- s.pop() delete the top element of stack, NOT return its value
- s.top() return the value of top element in stack, not deleting
- s.push(item) push new element in stack
Codes below show the five operations:
// number of elements we'll put in our stack
const stack<int>::size_type stk_size = 10;
stack<int> intStack; // empty stack
// fill up the stack
int ix = 0;
while(intStack.size() != stk_size)
// use postfix increment; want to push old value onto intStack
intStack.push_back(ix++); // intStack holds 0...9 inclusive
int error_cnt = 0;
while(intStack.empty() == false)
{
int value = intStack.top();
// read the top element of the stack
if(value != --ix)
{
cerr << "oops! expected " << ix
<< " received " << value << endl;
++error_cnt;
}
intStack.pop(); // pop the top element, and repeat
}
cout << "Our program ran with "
<< error_cnt << " errors!" << endl;