C++ 如何打印出 std::stack 的内容并返回其大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12631514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I print out the contents of std::stack and return its size?
提问by John
In c++ how can I print out the contents of my stack and return its size?
在 C++ 中,如何打印堆栈的内容并返回其大小?
std::stack<int> values;
values.push(1);
values.push(2);
values.push(3);
// How do I print the stack?
回答by sehe
You could make a copy of the stack and pop items one-by-one to dump them:
您可以制作堆栈的副本并逐个弹出项目以转储它们:
#include <iostream>
#include <stack>
#include <string>
int main(int argc, const char *argv[])
{
std::stack<int> stack;
stack.push(1);
stack.push(3);
stack.push(7);
stack.push(19);
for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
std::cout << dump.top() << '\n';
std::cout << "(" << stack.size() << " elements)\n";
return 0;
}
Output
输出
19
7
3
1
(4 elements)
See it live here: http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f
在这里看到它:http: //liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f
回答by Cheers and hth. - Alf
Both std::stack
and std::queue
are wrappers around a general container. That container is accessible as the protected
member c
. Using c
you can gain efficientaccess to the elements; otherwise, you can just copy the stack or queue and destructively access the elements of the copy.
这两个std::stack
和std::queue
周围一般的容器包装。该容器可作为protected
成员访问c
。使用c
您可以获得对元素的有效访问;否则,您可以只复制堆栈或队列并破坏性地访问副本的元素。
Example of using c
:
使用示例c
:
#include <iostream> // std::wcout, std::endl
#include <stack> // std::stack
#include <stddef.h> // ptrdiff_t
using namespace std;
typedef ptrdiff_t Size;
typedef Size Index;
template< class Elem >
Size nElements( stack< Elem > const& c )
{
return c.size();
}
void display( stack<int> const& numbers )
{
struct Hack
: public stack<int>
{
static int item( Index const i, stack<int> const& numbers )
{
return (numbers.*&Hack::c)[i];
}
};
wcout << numbers.size() << " numbers." << endl;
for( Index i = 0; i < nElements( numbers ); ++i )
{
wcout << " " << Hack::item( i, numbers ) << endl;
}
}
int main()
{
stack<int> numbers;
for( int i = 1; i <= 5; ++i ) { numbers.push( 100*i ); }
display( numbers );
}
回答by jweyrich
The only way to print the elements of a std::stack
without popping them, is to write an adapter that extends std::stack
(here's an example). Otherwise, you should replace your stack with a std::deque
.
打印 a 的元素std::stack
而不弹出它们的唯一方法是编写一个扩展的适配器std::stack
(这里有一个例子)。否则,您应该用std::deque
.
回答by Armin Montigny
Hm, a nearly 10 years old question. Anyway, here an additional answer.
嗯,一个将近 10 年的问题。无论如何,这里有一个额外的答案。
First: The size of a stack is given by std::stack.size().
第一:堆栈的大小由 std::stack.size() 给出。
Then, in modern C++ the STL with algorithms is used more and more. So the following solution makes use of that. The precondition is that a stack uses contiguous memory. That is guaranteed at the moment.
然后,在现代 C++ 中,越来越多地使用带有算法的 STL。因此,以下解决方案利用了这一点。前提是堆栈使用连续内存。这在目前是有保证的。
Output is done via a one liner.
输出是通过单衬完成的。
See the following example:
请参阅以下示例:
#include <vector>
#include <stack>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <sstream>
using Number = int;
using UnderlyingContainer = std::vector<Number>;
using Stack = std::stack< Number, UnderlyingContainer>;
std::istringstream testData("5 8 1 4 9 3");
int main()
{
// Put the test data onto the stack
Stack stack{ UnderlyingContainer {std::istream_iterator<Number>(testData),std::istream_iterator<Number>()} };
// Print the test data
if (not stack.empty())
std::copy(&stack.top() + 1 - stack.size(), &stack.top() + 1, std::ostream_iterator<Number>(std::cout, "\n"));
return 0;
}
This is completely valid and reliable code. Here a little bit more explanation.
这是完全有效和可靠的代码。这里稍微解释一下。
We want to output the data, so we copy it to an ostream_iterator. The ostream_iterator takes a reference to a stream (Yes you can put also an open ofstream) and the deliminator. Maybe you want to use a " ".
我们想输出数据,所以我们将它复制到 ostream_iterator。ostream_iterator 引用一个流(是的,你也可以放一个开放的 ofstream)和定界符。也许您想使用“ ”。
The source for the copy are 2 iterators. And, yes, pointers are iterators. And, we make use of the guaranteed contiguous memory for a std::stack. So, we simply calculate 2 pointers and hand them over to std::copy.
副本的来源是 2 个迭代器。而且,是的,指针是迭代器。并且,我们将保证的连续内存用于 std::stack。因此,我们只需计算 2 个指针并将它们交给 std::copy。
And if you want to use explicit iterators. Here we go . .
如果你想使用显式迭代器。开始了 。.
#include <vector>
#include <stack>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <sstream>
using Number = int;
using UnderlyingContainer = std::vector<Number>;
using Stack = std::stack< Number, UnderlyingContainer>;
using StackIterator = const Number *;
std::istringstream testData("5 8 1 4 9 3");
int main()
{
// Put the test data onto the stack
Stack stack{ UnderlyingContainer {std::istream_iterator<Number>(testData),std::istream_iterator<Number>()} };
// Print the test data
// Get iterators
StackIterator end = &stack.top() + 1;
StackIterator begin = end - stack.size();
if (not stack.empty())
std::copy(begin, end, std::ostream_iterator<Number>(std::cout, "\n"));
return 0;
}
So you can create iterators for a stack. But, caveat:
因此,您可以为堆栈创建迭代器。但是,警告:
The std::stack intentionally hides its elements under the hood. So, if you write-access the data, I would see it as a design fault. Read-access through const pointers/iterators is for me OK. But maybe you should better use a std::vector . . .
std::stack 有意将其元素隐藏在引擎盖下。因此,如果您对数据进行写访问,我会将其视为设计错误。通过 const 指针/迭代器的读取访问对我来说是可以的。但也许你应该更好地使用 std::vector 。. .
回答by Morendo
http://www.cplusplus.com/reference/stl/stack/for the size it's easy use :
http://www.cplusplus.com/reference/stl/stack/易于使用的大小:
cout << mystack.size();
For the rest i didn't see anything about in the doc but you should print the content of your stack when you push it, or have a list with it to keep a record of the element just in order to print it, don't forget to delete it when you're done testing
其余的我在文档中没有看到任何内容,但是您应该在推送堆栈时打印堆栈的内容,或者有一个包含它的列表来保留元素的记录,只是为了打印它,不要完成测试后忘记删除它