Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+;中,如果没有pop()函数,如何返回堆栈的第二个元素+;?_C++_Data Structures_Stack - Fatal编程技术网

C++ 在C+;中,如果没有pop()函数,如何返回堆栈的第二个元素+;?

C++ 在C+;中,如果没有pop()函数,如何返回堆栈的第二个元素+;?,c++,data-structures,stack,C++,Data Structures,Stack,我需要帮助以返回不带pop()的堆栈的第二个元素?但我不知道怎么用 我的代码: stack<int> st; st.push(10); st.push(20); st.top(); // return 20 stack-st; 圣普什(10); 圣普什(20); 圣托普();//返回20 如何使这个函数在没有pop()的情况下返回10 谢谢 顺便说一句,对不起我的英语。你不能用stack,因为它应该是后进先出,如果你想要这样的行为,请使用其他顺序容器,如vector,deque或

我需要帮助以返回不带pop()的堆栈的第二个元素?但我不知道怎么用

我的代码:

stack<int> st;
st.push(10);
st.push(20);
st.top(); // return 20
stack-st;
圣普什(10);
圣普什(20);
圣托普();//返回20
如何使这个函数在没有pop()的情况下返回10

谢谢


顺便说一句,对不起我的英语。

你不能用
stack
,因为它应该是后进先出,如果你想要这样的行为,请使用其他顺序容器,如
vector
deque
list

如果你这样做,它将不再是一个堆栈,根据定义。

如果要检索第二个元素,为什么需要
堆栈作为表示?堆栈是后进先出的表示形式,因此理论上不检索第二个元素,只检索添加的最后一个元素


使用其他表示法,例如提到的@Naveen。

我想您是在尝试模拟基于堆栈的机器

以下是使用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-st;
圣普什(10);
圣普什(20);
int top=st.top();//返回20
圣普();
int second=st.top();//返回10
圣普什(顶部);

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

无法使用pop()是一种奇怪的人为限制。如果这是一个家庭作业或面试问题,我认为你遗漏了一些东西,因为根据你目前发布的内容,没有解决方案。同意,他应该使用vector。方法push_-back和pop_-back对模拟堆栈很有用,+他可以做很多其他有用的事情。我甚至不知道为什么标准会被std::stack的存在所污染。没有人会说处理器没有堆栈,但是您可以随时访问处理器堆栈的任何元素(在大多数流行的体系结构上)。