[data structure] STL implementation queue

UltraMar1ne 2022-05-22 12:23:27 阅读数:368

datastructurestlimplementationqueue

queue It's the familiar queue , It's a FIFO compliance (FIFO) Principle data structure , This article will introduce the related class methods .

One 、 References to header files

Want to use STL Of queue Class container , We need to first reference the corresponding header file :

#include<queue>

In fact, in most cases, for convenience , You can only quote one universal header file ( Lazy me ):

#include<bits/stdc++.h>

Two 、 Create objects

After referencing the header file , Need to initialize an object , Our next operations are carried out on this object :

queue<ElemType> q;

Old rules ,ElemType Is the type of data you need

3、 ... and 、 Several commonly used methods

1. Determines if the queue is empty :

q.empty();

This is a bool Type of function , If the queue is empty , return true, Otherwise return to false

2. Return the length of the queue :

int length=q.size();

3. Get queue elements :

ElemType elem=q.front();
ElemType elem=q.back();

They are the first and last elements of the queue

4. Insert... Into the queue 、 Pop up elements :

q.push(ElemType elem);
q.pop(ElemType elem);

When it pops out, it's gone ~

5. On the traversal of circular queue :

int elem; // Here we use elem For example 
for(int i=0;i<n;i++){
 // there n Is the number of data you want to enter 
if(q.size()+1<n){
 // Judge whether the queue is full 
cin>>elem;
q.push(elem) // If you are dissatisfied, join the team 
}
else{

cin>>elem; // When it's full, just input , The queue turns a blind eye QAQ
}
}

The traversal output in the back is also very simple , no need iterator Iterator traversal :

for(;!q.empty();q.pop()){
 // On the premise of not empty, play while outputting 
cout<<q.front()<<" ";
}

You can even use while loop , The principle is the same :

while(!q.empty()){

cout<<q.front()<<" ";
q.pop();
}

Four 、 About deque Double queue

Another thing to add is ,STL A data structure type is also provided ”deque“, It's a two-way queue , Double queue for short , It is stored in the header file <deque> in . But double queues are not recommended here .

Why??

Dual queues do work in both directions , But all its operations can be realized through stack and ordinary queue , It may even be better than using it directly deque It's simpler .

copyright:author[UltraMar1ne],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/142/202205211828224031.html