Copy std::stack into an std::vector

后端 未结 6 866
不思量自难忘°
不思量自难忘° 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条回答
  •  终归单人心
    2021-02-07 09:33

    I don't have a reference to the standard to back this up unfortunately, but there aren't many ways in which it could go wrong I guess:

    • Specifying std::vector as the container type means that the elements must be stored in a std::vector.
    • st.top() must return a reference to an element in the underlying container (i.e. an element in the std::vector. Since the requirements on the container are that it supports back(), push_back() and pop_back(), we can reasonably assume that top() returns a reference to the last element in the vector.
    • end therefore points to one past the last element.
    • start therefore points to the beginning.

    Conclusion: Unless the assumption was wrong, it must work.

    EDIT: And given the other answer's reference to the standard, the assumption is correct, so it works.

提交回复
热议问题