第 18.7 節

queue container

0瀏覽次數0訪問次數--跳出率--平均停留

queue container

Queue Basic Concepts

Concept: A Queue is a First In First Out (FIFO) data structure, which has two ends.

Description: 2015-11-15_214429

Queue container allows adding elements from one end and removing elements from the other end.

In a queue, only the head and tail are accessible to external operations, which means that queue does not permit traversal behavior.

Adding data to a queue is called --- enqueue push

Removing data from a queue is called --- dequeue pop

Queues in Life:

1547606785041

Common interfaces for queue

Function Description: Common public interfaces for stack container

Constructor:

  • queue<T> que; //queue is implemented using template classes, the default constructor form for queue objects
  • queue(const queue &que); //copy constructor

Assignment operation:

  • queue& operator=(const queue &que); //overloading the equality operator

Data Access:

  • push(elem); //add elements to the end of the queue
  • pop(); //Remove the first element from the front of the queue
  • back(); //Returns the last element
  • front(); //return the first element

Size Operations:

  • empty(); //Check if the stack is empty
  • size(); //return stack size

Example:

#include <iostream>
#include <queue>
#include <string>

using namespace std;

class Person
{
public:
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }

    string m_Name;
    int m_Age;
};

void test01() {

    //创建队列
    queue<Person> q;

    //准备数据
    Person p1("唐僧", 30);
    Person p2("孙悟空", 1000);
    Person p3("猪八戒", 900);
    Person p4("沙僧", 800);

    //向队列中添加元素  入队操作
    q.push(p1);
    q.push(p2);
    q.push(p3);
    q.push(p4);

    //队列不提供迭代器,更不支持随机访问 
    while (!q.empty()) {
        //输出队头元素
        cout << "队头元素-- 姓名: " << q.front().m_Name 
              << " 年龄: "<< q.front().m_Age << endl;
        
        cout << "队尾元素-- 姓名: " << q.back().m_Name  
              << " 年龄: " << q.back().m_Age << endl;
        
        cout << endl;
        //弹出队头元素
        q.pop();
    }

    cout << "队列大小为:" << q.size() << endl;
}

int main() {

    test01();


    return 0;
}

运行结果:

队头元素-- 姓名: 唐僧 年龄: 30
队尾元素-- 姓名: 沙僧 年龄: 800

队头元素-- 姓名: 孙悟空 年龄: 1000
队尾元素-- 姓名: 沙僧 年龄: 800

队头元素-- 姓名: 猪八戒 年龄: 900
队尾元素-- 姓名: 沙僧 年龄: 800

队头元素-- 姓名: 沙僧 年龄: 800
队尾元素-- 姓名: 沙僧 年龄: 800

队列大小为:0

Summary:

  • Enqueue --- push
  • dequeue --- pop
  • Return the front element --- front
  • Return the element at the back of the queue --- back
  • Check if the queue is empty --- empty
  • Return queue size --- size
音乐页