I need to be able to access and move elements within a stack (C++ STL). I have tried using an iterator to navigate to the element that I want to move, but then I realized that I don't know how to remove that element. Is there a way to use pop to remove the element that my iterator is pointing to? Can you even use iterators on a stack? I'm kind of lost. Any help would be greatly appreciated.
Accessing elements in a stack?
Collapse
X
-
A stack is a LIFO queue (last-in-first-out) so there is no provision to access members of the stack or move them around.
That is done using a vector. -
Originally posted by weaknessforcatsA stack is a LIFO queue (last-in-first-out) so there is no provision to access members of the stack or move them around.
That is done using a vector.
"Write a function
Code:template <typename T> T second(const stack<T>& s);
For this part I just popped to T temp then used top( ) then push(temp) and I output the value that I got from top( )
But for part b:
Write a function
Code:template <typename T> void n2top(stack<T>& s, int n);
So I'm still not really sure what its looking for.Comment
-
Oh, I see now. An academic exercise.
To see the nth element of a stack,
1) pop all the elements before n and push them into a second stack.
2) do a top() to see the value of the nth element
3) push all of the elements from the second stack back onto the first stack.
4) delete the second stackComment
-
Originally posted by scuba6388thanks everyone, I figured it out before the previous post, but that just confirms it. It seems like a stupid question now that I figured it out, so thanks everyone for your help.Comment
Comment