C++模板库STL——stack

已经造好的轮子~
0、访问(只能访问栈顶)

#include <stdio.h>
#include <stack>
using namespace std;

int main(){
	stack<int>st;
	for(int i = 1;i <= 5;i++){
		st.push(i);
	}
	printf("%d\n",st.top());//访问栈顶元素(也只能这么访问) 
	return 0;
}

1、一些函数
pop()

#include <stdio.h>
#include <stack>
using namespace std;

int main(){
	stack<int>st;
	for(int i = 1;i <= 5;i++){
		st.push(i);
	}
	for(int i = 1;i <= 3;i++){
		st.pop();//连续三次将栈顶元素出栈 
	}
	printf("%d\n",st.top());
	return 0;
}

empty()

#include <stdio.h>
#include <stack>
using namespace std;

int main(){
	stack<int>st;
	if(st.empty() == true){
		printf("Empty\n");
	}
	else{
		printf("Not Empty\n");
	}
	st.push(1);
	if(st.empty() == true){
		printf("Empty\n");
	}
	else{
		printf("Not Empty\n");
	}
	return 0;
}

size()
返回栈内元素个数

#include <stdio.h>
#include <stack>
using namespace std;

int main(){
	stack<int>st;
	for(int i = 1;i <= 5;i++){
		st.push(i);
	}
	printf("%d\n",st.size());
	return 0;
}
发布了121 篇原创文章 · 获赞 3 · 访问量 2966

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104093278