将 std::stack 复制到 std::vector

Copy std::stack into an std::vector(将 std::stack 复制到 std::vector)
本文介绍了将 std::stack 复制到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)