zoukankan      html  css  js  c++  java
  • 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:

    #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;
    
  • 相关阅读:
    【Linux】Linux服务器(centos7)安装配置 redis
    【java】使用 starter 的方式在 SpringBoot 中整合 Shiro
    【Docker】使用 Docker 基于centos7 构建 java 环境容器
    c#经典三层框架中的SqlHelper帮助类
    SOD框架的Model、连接数据库及增删改查
    用bat文件更改ip地址
    postgresql 创建并使用uuid作为唯一主键
    postgresql 查询字符串中是否包含某字符的几种写法
    pycharm激活码
    c# DataTable第二行改为各列标题字段
  • 原文地址:https://www.cnblogs.com/kid551/p/4266903.html
Copyright © 2011-2022 走看看