c++ stl 栈、top()返回值

push() 入栈 返回空
pop() 出栈 返回空
top() 返回栈顶元素的引用。
如果

int r = s.top();

r是一个新的变量,变量的值是栈顶元素的值
如果

int &t = s.top();

t是栈顶元素的引用,相当于栈顶元素的别名。

#include <stack>
#include <iostream>
using namespace std;

int main()
{
    
    
	stack<int> s;
	s.push(1);
	s.push(2);// [1,2>
	cout<<s.top();
	s.top() = 0;// [1,0>
	cout<<s.top();
	int &a = s.top();
	a=3;// [1,3>
	cout<<s.top();
	int b = s.top();
	b=4;// [1,3>
	cout<<s.top();
} 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wx_assa/article/details/104318840
今日推荐