栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Cpp-Stack&&Queue

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Cpp-Stack&&Queue

stack 常用接口

功能描述:栈容器常用的对外接口

构造函数:

  • stack stk; //stack采用模板类实现, stack对象的默认构造形式
  • stack(const stack &stk); //拷贝构造函数

赋值操作:

  • stack& operator=(const stack &stk); //重载等号操作符

数据存取:

  • push(elem); //向栈顶添加元素
  • pop(); //从栈顶移除第一个元素
  • top(); //返回栈顶元素

大小操作:

  • empty(); //判断堆栈是否为空
  • size(); //返回栈的大小
#include 
#include 
using namespace std;

void test()
{
    stack s;

    s.push(1);
    s.push(2);
    s.push(3);

    cout << "size of the stack is: " << s.size() << endl;

    while(!s.empty()){
        cout << "top element of stack is " << s.top() << endl;
        s.pop();
    }

    cout << "size of the stack is: " << s.size() << endl;
}

int main(){
    test();
    return 0;
}
queue 常用接口

功能描述:栈容器常用的对外接口

构造函数:

  • queue que; //queue采用模板类实现,queue对象的默认构造形式
  • queue(const queue &que); //拷贝构造函数

赋值操作:

  • queue& operator=(const queue &que); //重载等号操作符

数据存取:

  • push(elem); //往队尾添加元素
  • pop(); //从队头移除第一个元素
  • back(); //返回最后一个元素
  • front(); //返回第一个元素

大小操作:

  • empty(); //判断堆栈是否为空
  • size(); //返回栈的大小
#include 
#include 
#include 
using namespace std;

class Person
{
    public:
        Person(string name, int age)
        {
            this->m_name = name;
            this->m_age = age;
        }

        string m_name;
        int m_age;
};

void test()
{
    queue q;

    Person p1("Alice", 30);
    Person p2("Bob", 40);
    Person p3("Cace", 50);
    Person p4("David", 60);

    q.push(p1);
    q.push(p2);
    q.push(p3);
    q.push(p4);

    while(!q.empty()){
        cout << "top of queue: " << endl << "name: " << q.front().m_name << endl
             << "age: " << q.front().m_age << endl;

        cout << "end of queue: " << endl << "name: " << q.back().m_name << endl
             << "age: " << q.back().m_age << endl;
        
        cout << endl;
        q.pop();
    }

    cout << "size of queue is: " << q.size() << endl;
}

int main(){
    test();
    return 0;
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656728.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号