Copy std::stack into an std::vector

后端 未结 6 876
不思量自难忘°
不思量自难忘° 2021-02-07 09:02

Is the following code guaranteed by the standard to work(assuming st is not empty)?

#include 
#include 
int main()
{
   extern std::st         


        
6条回答
  •  旧时难觅i
    2021-02-07 09:23

    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 st;
       int* end   = &st.back() + 1;
       int* begin = end - st.size();
       std::vector 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.

提交回复
热议问题