C++ stack容器 总结

-----------------------------------stack 容器

  stack是一种先进后出(first in last out,FILO)的数据结构,他只有一个出口,stack只允许在栈顶新增元素,移除元素,获得元素。

但是除了顶端外,其他地方不允许存取元素,只有栈顶元素才可以被外界使用,也就是说,stack不具备遍历行为,没有迭代器

--------------特性总结:

且不支持随机存取,只能通过top从栈顶获取和删除元素

  入栈顺序为:a b c d e

  出栈顺序为:e d c b a

--------------stack  API

stack 构造函数

  stack<T> stkT;  stack采用模板类实现,stack对象的默认操作形式

  stack (const stack& stk);   拷贝构造函数

stack 赋值操作

  stack& operator= (const stack& stk);    重载=操作符

stack 数据存储操作

  push(elem); 向栈顶添加元素

  pop();  从栈顶移除第一个元素

  top();  返回栈顶元素

stack 大小操作

  empty();    判断堆栈是否为空

  size(); 返回堆栈大小

#include<iostream> #include<stack> #include<string> using namespace std; void test01 () { //初始化 stack<int> s1; stack<int> s2(s1); //stack操作 s1.push(10); s1.push(20); s1.push(30); s1.push(40); s1.push(100); cout << "栈顶元素: " << s1.top() << endl; //删除栈顶元素 s1.pop(); //打印栈容器数据 while (!s1.empty()) { cout << s1.top() << " "; s1.pop(); } cout << endl; cout << "size: " << s1.size() << endl; } class Person { public: Person () {} Person (string name,int age):name(name),age(age) {} public: string name; int age; }; //stack 存放对象 void test02 () { stack<Person> s; Person p1("zhang",11),p2("li",22),p3("sun",33); //压入对象 s.push(p1); s.push(p2); s.push(p3); cout << "size: " << s.size() << endl; //打印对象数据 while (!s.empty()) { cout << "name: " << s.top().name << " age: " << s.top().age << endl; s.pop(); } } //stack 存放对象指针 void test03 () { stack<Person*> s; Person p1("zhang",11),p2("li",22),p3("sun",33); //压入对象地址 s.push(&p1); s.push(&p2); s.push(&p3); cout << "size: " << s.size() << endl; //打印对象数据 while (!s.empty()) { cout << "name: " << s.top()->name << " age: " << s.top()->age << endl; s.pop(); } } int main () { test01(); test02(); test03(); return 0; }

 

var code = "6090004a-6d07-4e91-9dac-bbe2e5fac8db"


__EOF__

本文作者KAZU0105
本文链接https://www.cnblogs.com/0105XiaoyeZhang/p/17065937.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   KAZU0105  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示