在C++中,你可以使用top()
函数来获取栈顶元素。以下是一个示例:
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
// 获取栈顶元素
int topElement = myStack.top();
std::cout << "栈顶元素: " << topElement << std::endl;
return 0;
}
输出:
栈顶元素: 3
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:c++ stack类如何获取栈顶元素