Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy std::stack into an std::vector

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);
}
like image 803
Armen Tsirunyan Avatar asked Dec 03 '10 13:12

Armen Tsirunyan


3 Answers

Yes.

std::stack is just a container adapter.

You can see that .top() is actually (§23.3.5.3.1)

reference top() { return c.back(); }

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);

And as std::vector is guaranteed to be continuous there should be no problem.

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.

like image 50
ronag Avatar answered Oct 14 '22 14:10

ronag


Only std::vector is guaranteed by C++03 to have contiguous elements (23.4.1). In C++1x this will be extended to std::string as well (defect #530).

like image 6
Daniel Lidström Avatar answered Oct 14 '22 12:10

Daniel Lidström


Yes, it's guaranteed. Vectors are guaranteed to use contiguous storage, so your code will work. It's a bit cludgy though - and if someone changes the underlying container type of the stack, your code will continue to compile without errors, yet the runtime behaviour will be broken.

like image 2
JoeG Avatar answered Oct 14 '22 13:10

JoeG