Hmm, almost a 10 year question. Anyway, here is an additional answer.
Modern C ++ STL with algorithms is used more and more. So the following solution uses this. A prerequisite is that the stack uses continuous memory. This is guaranteed at the moment.
Conclusion is carried out through one liner.
See the following example:
#include <vector> #include <stack> #include <iostream> #include <algorithm> #include <iterator> #include <sstream> using Number = int; using UnderlyingContainer = std::vector<Number>; using Stack = std::stack< Number, UnderlyingContainer>; std::istringstream testData("5 8 1 4 9 3"); int main() { // Put the test data onto the stack Stack stack{ UnderlyingContainer {std::istream_iterator<Number>(testData),std::istream_iterator<Number>()} }; // Print the test data if (not stack.empty()) std::copy(&stack.top() + 1 - stack.size(), &stack.top() + 1, std::ostream_iterator<Number>(std::cout, "\n")); return 0; }
This is fully valid and reliable code. Here are some more explanations.
We want to output the data, so copy it to ostream_iterator. Ostream_iterator accepts a stream reference (yes, you can also specify an open stream) and a separator. Maybe you want to use "".
The source for the copy is 2 iterators. And yes, pointers are iterators. And we use guaranteed continuous memory for std :: stack. So we just compute 2 pointers and pass them to std :: copy.
And if you want to use explicit iterators. Like this. ,
#include <vector> #include <stack> #include <iostream> #include <algorithm> #include <iterator> #include <sstream> using Number = int; using UnderlyingContainer = std::vector<Number>; using Stack = std::stack< Number, UnderlyingContainer>; using StackIterator = const Number *; std::istringstream testData("5 8 1 4 9 3"); int main() { // Put the test data onto the stack Stack stack{ UnderlyingContainer {std::istream_iterator<Number>(testData),std::istream_iterator<Number>()} }; // Print the test data // Get iterators StackIterator end = &stack.top() + 1; StackIterator begin = end - stack.size(); if (not stack.empty()) std::copy(begin, end, std::ostream_iterator<Number>(std::cout, "\n")); return 0; }
This way you can create iterators for the stack. But, be careful:
Std :: stack intentionally hides its elements under the hood. So if you get access to the data for recording, I would consider this a design error. Read access through constant pointers / iterators is ok for me. But maybe you better use std :: vector. ,,