将std :: stack复制到std :: vector中 [英] Copy std::stack into an std::vector
问题描述
以下代码是否被标准保证可以正常工作(假设st不为空)?
Is the following code guaranteed by the standard to work(assuming st is not empty)?
#include <vector>
#include <stack>
int main()
{
extern std::stack<int, std::vector<int> > st;
int* end = &st.top() + 1;
int* begin = end - st.size();
std::vector<int> stack_contents(begin, end);
}
推荐答案
是.
std :: stack
只是一个容器适配器.
std::stack
is just a container adapter.
您可以看到 .top()
实际上是(§23.3.5.3.1)
You can see that .top()
is actually (§23.3.5.3.1)
reference top() { return c.back(); }
其中 c
是容器,在这种情况下为 std :: vector
Where c
is the container, which in this case is a std::vector
这意味着您的代码基本上被翻译为:
Which means that your code is basically translated into:
extern std::vector<int> st;
int* end = &st.back() + 1;
int* begin = end - st.size();
std::vector<int> stack_contents(begin, end);
并且由于确保 std :: vector
是连续的,因此应该没有问题.
And as std::vector
is guaranteed to be continuous there should be no problem.
但是,这并不意味着这是一个好主意.如果您需要使用这种"hacks",则通常表明设计不良.您可能想从一开始就使用 std :: vector
.
However, that does not mean that this is a good idea. If you need to use "hacks" like this it is generally an indicator of bad design. You probably want to use std::vector
from the beginning.
这篇关于将std :: stack复制到std :: vector中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!