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);
}
Yes.
std::stackis just a container adapter.You can see that
.top()is actually (§23.3.5.3.1)Where
cis the container, which in this case is astd::vectorWhich means that your code is basically translated into:
And as
std::vectoris 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::vectorfrom the beginning.