作者:王昊成(小红书:秋来拾光),无所不能哈基咪
本文由同学分享个人经验,仅供学习交流,严禁倒卖。 具体要求请以学校及学院最新发布的信息为准。
stack 容器(栈)
stack 容器(栈)
ppt例
//Stack.h
const int maxsize = 6;
class Stack {
float data[maxsize];
int top;
public:
Stack(void);
~Stack(void);
bool empty(void);
void push(float a);
float pop(void);
};
//Stack.cpp
#include"Stack.h"
#include<iostream>
using namespace std;
Stack::Stack(void) {
top = 0;
cout << "stack initialized." << endl;
}
Stack::~Stack(void) {
cout << "stack destroyed." << endl;
}
bool Stack::empty(void) {
return top == 0 ? true : false;
}
void Stack::push(float a) {
if (top == maxsize) {
cout << "stack is full!" << endl;
return;
}
data[top] = a;
top++;
}
float Stack::pop(void) {
if (top == 0) {
cout << "Stack is underflow!" << endl;
return 0;
}
top--;
return data[top];
}
//Main.cpp
#include"Stack.h"
#include<iostream>
using namespace std;
int main() {
Stack s1, s2;
int i;
//第一组入栈:2 4 6 8 10 12
for(i = 1;i <= maxsize;i++)
s1.push(2 * i);
//全部出栈打印:12 10 8 6 4 2
for(i = 1;i <= maxsize;i++)
cout<<s1.pop()<<" ";
//第二组入栈:2.5 5 7.5 10 12.5 15
for(i = 1;i <= maxsize;i++)
s1.push(2.5*i);
//s1出栈→s2入栈
for(i = 1;i <= maxsize;i++)
s2.push(s1.pop());
cout << endl;
//s2全部出栈打印
do
cout << s2.pop() << " ";
while (!(s2.empty()));
cout << endl;
return 0;
}
stack initialized.
stack initialized.
12 10 8 6 4 2
2.5 5 7.5 10 12.5 15
stack destroyed.
stack destroyed.
一、头文件
#include<stack>特性:先进后出(FILO),仅能访问、操作栈顶元素,无法随机访问中间元素存储规则:末尾入栈、末尾出栈,不支持遍历除栈顶外的数据
二、容器声明格式
// 格式:stack<存储类型> 栈名;
stack<int> st1;
stack<double> st2;
stack<char> st3;
三、初始化格式
// 1.空栈初始化
stack<int> s1;// 2.拷贝已有栈初始化
stack<int> s2(s1);
四、常用成员函数调用格式
4.1 基础属性操作
empty():判断栈空,空返回 true,非空 false
bool flag = st.empty();
size():获取栈内有效元素个数
int len = st.size();
4.2 元素插入
push(val):元素入栈,添加至栈顶
st.push(5);
st.push(3.14);
4.3 元素删除
pop():删除栈顶元素,无返回值
st.pop();
4.4 元素查找 / 取顶
top():返回栈顶元素引用,只取值不删除
int x = st.top();
pop 只删不返回、top 只看不删,取 + 删组合:auto t=st.top(); st.pop();不能通过下标st[0]访问元素