在 Visual C++ 中使用 STL 队列类的成员函数

下面的示例代码演示如何在 Visual C++中使用 queue::pushqueue::popqueue::emptyqueue::backqueue::frontqueue::size STL 函数。 本文中的信息仅适用于非托管的 Visual C++ 代码。

原始产品版本: Visual C++
原始 KB 数: 157622

总结

适配器保存由 queue 支持的 queue容器类型定义的类型的对象。 支持的两个容器是 listdeque。 对象入push()并删除。pop() front() 返回 (也称为 FIFO)中 queue 最早的项,并 back() 返回插入到中 queue的最新项。

必需的标头

  • <queue>

原型

queue::push();
queue::pop();
queue::empty();
queue::back();
queue::front();
queue::size();

注意

原型中的类或参数名称可能与头文件中的版本不匹配。 一些已修改以提高可读性。

代码示例

此示例显示了使用 listdeque 容器实现的队列实现。

//////////////////////////////////////////////////////////////////////
// Compile options needed: none
// <filename> : queue.cpp
// Functions:
// queue::push(), queue::pop(), queue::empty(), queue::back(),
// queue::front(),queue::size()
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
//////////////////////////////////////////////////////////////////////

/* Compile options needed: /GX */
#include <list>
#include <iostream>
#include <queue>
#include <deque>
using namespace std;

#if _MSC_VER > 1020  // if VC++ version is > 4.2
    using namespace std; // std c++ libs implemented in std
#endif

// Using queue with list
typedef list<int, allocator<int>> INTLIST;
typedef queue<int, INTLIST> INTQUEUE;

// Using queue with deque
typedef deque<char *, allocator<char *>> CHARDEQUE;
typedef queue<char *, CHARDEQUE> CHARQUEUE;
void main(void)
{
    int size_q;
    INTQUEUE q;
    CHARQUEUE p;

    // Insert items in the queue(uses list)
    q.push(42);
    q.push(100);
    q.push(49);
    q.push(201);

    // Output the item inserted last using back()
    cout << q.back() << endl;

    // Output the size of queue
    size_q = q.size();
    cout << "size of q is:" << size_q << endl;

    // Output items in queue using front()
    // and use pop() to get to next item until
    // queue is empty
    while (!q.empty())
    {
        cout << q.front() << endl;
        q.pop();
    }

    // Insert items in the queue(uses deque)
    p.push("cat");
    p.push("ape");
    p.push("dog");
    p.push("mouse");
    p.push("horse");

    // Output the item inserted last using back()
    cout << p.back() << endl;

    // Output the size of queue
    size_q = p.size();
    cout << "size of p is:" << size_q << endl;

    // Output items in queue using front()
    // and use pop() to get to next item until
    // queue is empty
    while (!p.empty())
    {
        cout << p.front() << endl;
        p.pop();
    }
}

程序输出

201
size of q is:4
42
100
49
201
horse
size of p is:5
cat
ape
dog
mouse
horse

参考

有关 STL queue 类的成员函数的相同信息,请参阅 队列