【C++标准库】特殊容器

特殊容器,又称为容器适配器(Container Adapter),它们改造了标准STL容器,使之满足特殊的要求。

Stack堆栈

使用stack时,需包含头文件<stack>

  • push()  将一个元素压入栈内
  • pop()   从栈内移除下一个元素,但是并不返回它
  • top()         返回栈内下一个元素,但并不移除它。

如果stack内没有元素,top()和pop()会导致不明确的行为,可采用size()或empty()来检查容器是否为空。

Queue队列

Queue实现出了一个FIFO先进先出的结构,是一个典型的数据缓冲构造。使用时需包含头文件<queue>

  • push() 将一个元素入队列
  • front()返回队列中第一个元素,但不移除元素
  • back()返回队列中最后一个元素,但不移除元素
  • pop()从队列中移除一个元素,但不返回它

如果队列内没有元素,front(),back()和pop()将导致不明确的行为,可采用size()或empty()来检查容器是否为空。

Priority Queue优先级队列

priority queue内的元素根据优先级进行了排序,使用时需包含头文件<queue>

  • push()将一个元素放入priority queue中
  • top()返回priority queue中第一个元素,但并不移除
  • pop()移除一个元素,但并不返回

如果优先级队列内没有元素,top()和pop()会导致不明确的行为,可采用size()或empty()来检查容器是否为空。

#include <iostream>
#include <queue>
using namespace std;

int main()
{
    priority_queue<float> q;
    q.push(66.6);
    q.push(22.2);
    q.push(44.4);

    cout << q.top() << endl;
    q.pop();
    cout << q.top() << endl;
    q.pop();
    q.push(11.1);
    q.push(55.5);
    q.push(33.3);
    while (!q.empty())
    {
        cout << q.top() << endl;
        q.pop();
    }
    return 0;
}
View Code

 BitSet

BitSet构造出了一个内含bit或Boolean值且大小固定的array,当需要管理各式flag,并以flag任意组合来表现变量时,就可以运用bitset。

BitSet定义于头文件<bitset>中

/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <bitset>
#include <iostream>
using namespace std;

int main()
{
    // enumeration type for the bits
    // - each bit represents a color
    enum Color {
        red, yellow, green, blue, white, black, //...,
        numColors
    };

    // create bitset for all bits/colors
    bitset<numColors> usedColors;

    // set bits for two colors
    usedColors.set(red);
    usedColors.set(blue);

    // print some bitset data
    cout << "bitfield of used colors:   " << usedColors << endl;
    cout << "number   of used colors:   " << usedColors.count() << endl;
    cout << "bitfield of unused colors: " << ~usedColors << endl;

    // if any color is used
    if (usedColors.any()) 
    {
        // loop over all colors
        for (int c = 0; c < numColors; ++c) 
        {
            // if the actual color is used
            if (usedColors[(Color)c]) {
                //...
            }
        }
    }
}
View Code

原文地址:https://www.cnblogs.com/larry-xia/p/9504007.html