Container Adaptors

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:

1
2
#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:

1
2
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:

1
2
3
4
5
// 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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;

 

posted @   kid551  阅读(262)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示