C++ STL (6): queue container


1 Basic concepts of queue

Features : The queue queueis a first-in-first-out ( FIFO, First In First Out) data structure, including two exits , inTailInsert element ( 入队), inLeader of the teamDelete element ( 出队).
queue container
Head of line/Head of line :, the front()queue container allows elements to be removed from the head of the line .
Endback() of the queue :, the queue container allows adding elements from the end of the queue .

Note: In the queue, onlyTeam headwithTailCan be accessed and used by the outside world, soQueue does not allow traversal behavior

Join the team :, push()add elements to the end of the team.
Dequeue :, pop()remove elements from the head of the team/leader of the team.


2 queue common interface

Note: When using the queue container, you need to include the header file #include <queue>.

Constructor :
queue<T> que;: Default no-argument constructor, implemented by class template .
queue(const queue &que);: Copy the constructor, use the existing queue object to initialize a new object.

Assignment operation ::
queue& operator=(const queue &que);Overload the assignment operator, use the target queue container to assign a value to the current queue container.

Data access ::
push(elem);Add elements to the end of the team.
pop();: Remove the element from the head of the team.
front();: Return to the first element of the team (the first element ).
back();: Return to the tail element (the last element ).

Size operation :
empty();Determine whether the queue is empty.
size();: Return the size/length of the queue.

Example : common interface for queue

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

class Person {
    
    
public:
	string name;
	int level;

	Person(string name, int level) {
    
    
		this->name = name;
		this->level = level;
	}
};

int main() {
    
    
	//创建队列
	queue<Person> q;

	Person p1("唐僧", 30);
	Person p2("孙悟空", 99);
	Person p3("猪悟能", 60);
	Person p4("沙悟净", 50);

	//入队
	q.push(p1);
	q.push(p2);
	q.push(p3);
	q.push(p4);

	cout << "当前队列大小:" << q.size() << endl;	//4
	
	//循环出队
	while (!q.empty()) {
    
    
		cout << "当前队首元素:" << q.front().name << endl;
		cout << "当前队尾元素:" << q.back().name << endl;
		cout << "***********" << endl;
	
		//出队
		q.pop();
	}

	cout << "当前队列大小:" << q.size() << endl;	//0

	return 0;
}

Guess you like

Origin blog.csdn.net/newson92/article/details/113930794