C++标准库中的栈和队列

C++标准库提供了stack和queue容器适配器,stack以LIFO(后进先出)原则操作元素,而queue遵循FIFO(先进先出)原则。它们都支持empty、size等操作。可以使用stack<int> s和queue<int> q来定义,结构体可以通过typedef创建,然后存入stack和queue,如stack<Str> s; s.push(str); 或者从栈顶取出数据str = s.top();。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++标准库中的栈和队头文件

栈:    #include<stack>

队列:#include<queue>

stack:

stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:

  • empty
  • size
  • back
  • push_back
  • pop_back

queue:

queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front".

The underlying container may be one of the standard container class template or some other specifically designed container class. This underlying container shall support at least the following operations:
  • empty
  • size
  • front
  • back
  • push_back
  • pop_front
(以上摘自Cplusplus.com)


定义方式:

栈:stack<int> s;

队列:queue<int> q;


包含函数:


栈:

s.empty()如果栈为空返回true,否则返回false
s.size()   返回栈中元素的个数
s.pop() 删除栈顶元素但不返回其值
s.top()  返回栈顶的元素,但不删除该元素
s.push() 在栈顶压入新元素


队列:

q.empty()如果队列为空返回true,否则返回false
q.size()返回队列中元素的个数
q.pop() 删除队列首元素但不返回其值
q.front() 返回队首元素的值,但不删除该元素
q.push()  在队尾压入新元素
q.back() 返回队列尾元素的值,但不删除该元素



存入结构体

可以将结构体存入栈或队列中

比如存入栈:

在引入头文件#include<stack>之后:

typedef struct Str

{

int i;

int j;

}Str;


stack<Str>  s;

Str str;

Str.i = 0;

S.j = 0;

s.push(str);


也可将栈中的数据返回直接用结构体接收:

str = s.top();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值