gpt4 book ai didi

c++ - 在 C++ 中,如何在没有 pop() 函数的情况下返回堆栈的第二个元素?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:32 26 4
gpt4 key购买 nike

我需要帮助在没有 pop() 的情况下返回堆栈的第二个元素吗?但我不知道如何使用。

我的代码:

stack<int> st;
st.push(10);
st.push(20);
st.top(); // return 20

如何让这个函数在没有 pop() 的情况下返回 10;

谢谢。

附言对不起我的英语。

最佳答案

我假设您正在尝试模拟基于堆栈的机器?

这是用 std::stack 做的唯一方法:

stack<int> st;
st.push(10);
st.push(20);
int top = st.top(); // return 20
st.pop();
int second = st.top(); // return 10
st.push(top);

如果您想要其他行为,您必须自己实现具有更多功能的stack

关于c++ - 在 C++ 中,如何在没有 pop() 函数的情况下返回堆栈的第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com