How can I access the top element of a C++ stack?
In C++, you can use the top() function to access the top element of the stack. Here is an example:
#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;
}
Output:
Produce results
栈顶元素: 3