【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

猜你喜欢

转载自www.cnblogs.com/larry-xia/p/9504007.html