zoukankan      html  css  js  c++  java
  • STL--容器适配器(queue、priority_queue、stack)

    适配器(Adaptor)是提供接口映射的模板类。适配器基于其他类来实现新的功能,成员函数可以被添加、隐藏,也可合并以得到新的功能。
    STL提供了三个容器适配器:queue、priority_queue、stack。
    这些适配器都是包装了vector、list、deque中某个顺序容器的包装器。注意:适配器没有提供迭代器,也不能同时插入或删除多个元素。
     本文地址:http://www.cnblogs.com/archimedes/p/cpp-adapter.html,转载请注明源地址。

    队列(queue)

    先进先出(FIFO)的数据结构
    可供选择的容器只有deque和list。对大多数用途使用默认的deque。
    1、要用到头文件#include<queue>
    2、常用函数
    • queue<int> Q 声明一个int的空队列Q;
    • push() 将一个新元素接到队列的末端;
    • pop() 弹出队列中的第一个元素,返回的是一个void;
    • front() back() 存取队列中的第一个元素和最后一个元素,返回的是一个引用;
    • empty() 测试队列是否为空;
    • size() 获得队列中元素的个数;

    堆栈(stack)

    先进后出(FILO)的数据结构
    可以使用三个标准顺序容器vector、deque、list中的任何一个作为stack的底层模型。
    1、要用到头文件#include<stack>
    2、常用函数
    • stack<int> Q 声明一个int的空栈Q;
    • push() 将一个新元素接到栈的末端;
    • pop() 弹出栈中的末端元素,返回的是一个void;
    • top() 存取栈中的最后一个元素,返回的是一个引用;
    • empty() 测试栈是否为空;
    • size() 获得栈中元素的个数;
    <priority_queue> 内部实现: 堆
    priority_queue<T, Sequence, Compare>
    支持操作:
    push() O(logn)
    pop() O(logn)
    top() O(1)存取队列中的第一个元素,与queue不同
    See also: push_heap(), pop_heap() … in <algorithm>

    priority_queue用法举例

    #include <queue>
    #include <vector>
    using namespace std;
    priority_queue <int> maxheap;      //int最大堆
    struct cmp{
        bool operator()(int a,int b) 
        {return a > b;}
    };
    priority_queue <int,vector<int>,cmp> minheap;  //int最小堆

    priority_queue的比较函数

    优先级的比较函数,可以使用缺省默认,也可以重载自己编写的比较函数。
    1) 假设优先队列中的元素为结构体,要对其中某个变量排序。此时可以在结构体中重载操作符:
    priority_queue<int, vector<int>, cmp> Q;
    struct cmp{
            int seq;                //重载运算符号
            bool operator < (const Test &a) const {
                    return seq < a.seq;     // seq大的优先级高
            }
    };

    2)如果是根据与优先队列中某个元素相关的变量排序,且此变量不在结构体中,则可参考greater<int>() 的方式去重载(),具体做法如下:

    priority_queue<int, vector<int>, cmp> Q;
    struct cmp {
          bool operator()(int a, int b) { // d[a]小的优先级高
                  return d[a] > d[b];
            }
    };
  • 相关阅读:
    bootstrap
    jQuery-介绍 加载 选择器 样式操作 属性操作 绑定click事件
    javascript -- BOM,DOM
    前端 -- javas-基本语法/引用等
    fatal: remote origin already exists.报错
    git
    npm install 时总是报phantomjs-prebuilt@2.1.14安装失败
    JavaScript中设置元素class,添加/删除元素class的方法
    单选按钮点击相关文字选中
    JS/Jquery实现select选中option触发事件
  • 原文地址:https://www.cnblogs.com/wuyudong/p/cpp-adapter.html
Copyright © 2011-2022 走看看