1 Introduction
queue is a container adapter that provides a queue function, and its data structure is FIFO (first-in, first-out) first- in-first -out ;
queue is a wrapper for the container deque;
header files and definitions
#include <queue>
template<
class T,
class Container = std::deque<T>
> class queue;
2. Initialization
queue cannot be initialized directly, but can be initialized by copying;
example
#include <iostream>
#include <queue>
#include <string>
using sstring = std::string;
int main(int argc, char* argv[])
{
std::queue<sstring> que;
que.push("c++");
que.emplace("c");
que.push("shell");
que.emplace("Rust");
std::queue<sstring> que1 = que;
return 0;
}
3. use
Queue basic operations;
method | illustrate |
---|---|
operator= | assignment operation |
front() | return the first element of the queue |
back() | Returns the last element of the queue |
empty() | Determine whether the queue is empty |
size() | Return the size of the queue |
push() | insert element |
place() | Inserting elements is more efficient than push |
pop() | Delete the element at the head of the queue |
swap() | Exchange the elements of two queues |
example
/*
* @brief: queue
* @compile: g++ -g queue_main.cc -o d -std=c++11
* @author: your name
* @date: 2023/04/03
* @lastEditorDate:
*/
#include <iostream>
#include <queue>
#include <string>
#include <functional>
void printEnd(int32_t n){
for(size_t i =0; i<n;i++) std::cout<<std::endl;}
std::function<void(int32_t)> e = printEnd;
using sstring = std::string;
int main(int argc, char* argv[])
{
//front back empty size pop swap
//1.元素插入
std::queue<sstring> que;
que.push("c++");
que.emplace("c");
que.push("shell");
que.emplace("Rust");
que.emplace("linux");
que.emplace("golang");
std::queue<sstring> que1 = que;
//2.元素遍历
std::cout<<"[que value] is: ";e(1);
//pop()删除的是队首元素
for(;!que.empty();que.pop())
{
std::cout<<que.front()<<" ";
}
e(2);
//3.元素输出
que = que1;
std::cout<<"front element value si: "<<que.front();e(1);
std::cout<<"back element value si: "<<que.back();e(1);
std::cout<<"size of que value si: "<<que.size();e(2);
//4.元素的交换
std::queue<sstring> que2;
que2.swap(que1);
if(que.empty())
{
std::cout<<"empty";e(1);
}
else{
std::cout<<"not empty";e(1);
}
return 0;
}
output
[que value] is:
c++ c shell Rust linux golang
front element value si: c++
back element value si: golang
size of que value si: 6
not empty