C++使用stack栈,如何取得从栈底到栈顶所有内容
时间: 2023-11-27 08:52:52 浏览: 94
在C++中,stack栈是一个容器适配器,它提供了后进先出(LIFO)的数据结构。如果想要取得从栈底到栈顶所有内容,可以通过以下方式实现:
1. 先将stack栈中所有元素依次出栈,存储到一个临时的数组中,直到栈为空。
2. 然后将这个临时数组中的元素按照原来的顺序重新压入stack栈中。
3. 最后遍历stack栈中的元素,就可以按照从栈底到栈顶的顺序获取所有内容。
下面是示例代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
// 临时数组
int tmp[3];
int index = 0;
// 将stack栈中所有元素依次出栈,并存储到临时数组中
while (!s.empty())
{
tmp[index++] = s.top();
s.pop();
}
// 将临时数组中的元素按照原来的顺序重新压入stack栈中
for (int i = 0; i < index; i++)
{
s.push(tmp[i]);
}
// 遍历stack栈中的元素,按照从栈底到栈顶的顺序获取所有内容
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
return 0;
}
```
输出结果为:3 2 1,表示从栈底到栈顶所有内容。