笔记(六)——stack容器的基础理论知识

stack是堆栈容器,元素遵循先进后出的顺序。

头文件:#include<stack>

一、stack容器的对象构造方法

stack采用模板类实现默认构造

例如stack<T> vecT;

#include<iostream>
#include<stack>
using namespace std;
int main()
{
    stack<int> stInt;
    stack<float> stFloat;
    stack<string> stString;

    stInt.push(5);//在栈头添加元素
    stInt.pop();//在栈头删除元素
    stInt.push(6);//在栈头添加元素
    stInt.push(7);//在栈头添加元素
    stInt.push(8);//在栈头添加元素
    stInt.pop();//在栈头删除元素
    
    while(!stInt.empty())    
    {
        cout<<stInt.top()<<endl;
        stInt.pop();//在栈头删除元素
    } 
    //输出7,6   
    
    return 0;
}

stack对象的带参构造方式

1、stack<T> st1(st2);拷贝构造函数

2、stack& operator=(const stack &st);重载等号操作符。

#include<iostream>
#include<stack>
using namespace std;
int main()
{
    stack<int> stInt1;

    stInt1.push(5);//在栈头添加元素
    stInt1.pop();//在栈头删除元素
    stInt1.push(6);//在栈头添加元素
    stInt1.push(7);//在栈头添加元素
    stInt1.push(8);//在栈头添加元素
    stInt1.pop();//在栈头删除元素
    
        stack<int> stInt2(stInt1);
    stack<int> stInt3=stInt1;
    
    while(!stInt1.empty())    
    {
        cout<<stInt1.top()<<endl;
        stInt1.pop();//在栈头删除元素
    } 
    //输出7,6   
    
    while(!stInt2.empty())    
    {
        cout<<stInt2.top()<<endl;
        stInt2.pop();//在栈头删除元素
    } 
    //输出7,6 
    
    while(!stInt3.empty())    
    {
        cout<<stInt3.top()<<endl;
        stInt3.pop();//在栈头删除元素
    } 
    //输出7,6 
    
    return 0;
}

二、stack容器的大小

  1. stack.empty();//判断堆栈是否为空

  1. stack.size();//返回堆栈的大小

#include<iostream>
#include<stack>
using namespace std;
int main()
{
    stack<int> stInt1;

    stInt1.push(5);//在栈头添加元素
    stInt1.pop();//在栈头删除元素
    stInt1.push(6);//在栈头添加元素
    stInt1.push(7);//在栈头添加元素
    stInt1.push(8);//在栈头添加元素
    stInt1.pop();//在栈头删除元素
    
    int size=stInt1.size();
    cout<<size<<endl;
    //输出2    
    while(!stInt1.empty())    
    {
        cout<<stInt1.top()<<endl;
        stInt1.pop();//在栈头删除元素
    } 
    //输出7,6   
    
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值