• 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;
    
  • 相关阅读:
    给 Advice 传递参数
    jenkins 部署问题
    Linux里的2>&1究竟是什么
    记一次 Spring 事务配置踩坑记
    Netty
    springboot logback 集成
    SpringBoot-服务端参数验证-JSR-303验证框架
    mysql 数据库 简单存储过程游标使用
    SQL Case when 的使用方法
    解决Unsupported major.minor version 51.0错误
  • 原文地址:https://www.cnblogs.com/kid551/p/4266903.html
Copyright © 2020-2023  润新知