Store results of std::stack .pop() method into a variable
The standard library containers separate top()
and pop()
: top()
returns a reference to the top element, and pop()
removes the top element. (And similarly for back()
/pop_back()
etc.).
There's a good reason for this separation, and not have pop
remove the top element and return it: One guiding principle of C++ is that you don't pay for what you don't need. A single function would have no choice but to return the element by value, which may be undesired. Separating concerns gives the user the most flexibility in how to use the data structure. (See note #3 in the original STL documentation.)
(As a curiousum, you may notice that for a concurrent container, a pop
-like function is actually forced to remove and return the top value atomically, since in a concurrent context, there is no such notion as "being on top" (or "being empty" for that matter). This is one of the obvious examples of how concurrent data structures take a significant performance hit in order to provide their guarantees.)
C++ Stack; Remove top value and placing into variable
If you want get the value at the top of the stack, then use stack::top()
, not stack::pop()
and then call pop()
afterwards to remove the top element from the stack. So, you'd do:
int result2 = myStack.top();
myStack.pop();
Strange behaviour with std::stack, pop() returns same value
std::stack<uint8_t*> pendingNotification;
You have a stack of pointers. For this to make sense, you'd have to have a bunch of distinct objects for the stack to hold pointers to, and those objects would have to remain valid for as long as you intend to use the stack of pointers. Your code doesn't do this.
Don't create stacks of pointers unless you have a really good reason to. Instead, create stacks of data values.
Store results of std::stack .pop() method into a variable
The standard library containers separate top()
and pop()
: top()
returns a reference to the top element, and pop()
removes the top element. (And similarly for back()
/pop_back()
etc.).
There's a good reason for this separation, and not have pop
remove the top element and return it: One guiding principle of C++ is that you don't pay for what you don't need. A single function would have no choice but to return the element by value, which may be undesired. Separating concerns gives the user the most flexibility in how to use the data structure. (See note #3 in the original STL documentation.)
(As a curiousum, you may notice that for a concurrent container, a pop
-like function is actually forced to remove and return the top value atomically, since in a concurrent context, there is no such notion as "being on top" (or "being empty" for that matter). This is one of the obvious examples of how concurrent data structures take a significant performance hit in order to provide their guarantees.)
Why doesn't std::queue::pop return value.?
So, whats the difference, pop function could have done the same thing.
It could indeed have done the same thing. The reason it didn't, is because a pop that returned the popped element is unsafe in the presence of exceptions (having to return by value and thus creating a copy).
Consider this scenario (with a naive/made up pop implementation, to ilustrate my point):
template<class T>
class queue {
T* elements;
std::size_t top_position;
// stuff here
T pop()
{
auto x = elements[top_position];
// TODO: call destructor for elements[top_position] here
--top_position; // alter queue state here
return x; // calls T(const T&) which may throw
}
If the copy constructor of T throws on return, you have already altered the state of the queue (top_position
in my naive implementation) and the element is removed from the queue (and not returned). For all intents and purposes (no matter how you catch the exception in client code) the element at the top of the queue is lost.
This implementation is also inefficient in the case when you do not need the popped value (i.e. it creates a copy of the element that nobody will use).
This can be implemented safely and efficiently, with two separate operations (void pop
and const T& front()
).
How to store a value obtained from a vector `pop_back()` in C++?
It may sound as pop as in returning a value. But it actually doesn't. The standard says that vector::pop_back
should erase the last value, with no return value.
You can do:
auto val = a.back();
a.pop_back();
How can I print out the contents of std::stack and return its size?
You could make a copy of the stack and pop items one-by-one to dump them:
#include <iostream>
#include <stack>
#include <string>
int main(int argc, const char *argv[])
{
std::stack<int> stack;
stack.push(1);
stack.push(3);
stack.push(7);
stack.push(19);
for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
std::cout << dump.top() << '\n';
std::cout << "(" << stack.size() << " elements)\n";
return 0;
}
Output
19
7
3
1
(4 elements)
See it live here: http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f
C++, stack and pointers of struct
void Search(Somethink* array_Somethink, int s, int d,) {
stack1.push(&(array_Somethink[s])); //
while (!stack1.empty()) {
int i = 0;
array_Somethink[i] = *(stack1.top());
stack1.pop();
i++;
}
}
My modified code assumes, you have "owning" pointers to the elements on the stack somewhere else. If that is not the case, you would end with memory leaks here, as the pointers in the stack become dangling objects (leaks).
In order to avoid the potential for memory leaks, here, it might be a good idea if you used std::shared_ptr<Somethink>
instead of raw pointers. Then, your stack would become a std::stack< std:shared_ptr<Somethink> >
.
For details on std::stack operations empty(),pop(),top()
, see std::stack
in the usual place.
There, you will find explanations such as this:
std::stack::top
C++ Containers library std::stack
reference top();
const_reference top() const;
Returns reference to the top element in the stack. This is the most recently pushed element. This element will be removed on a call to pop(). Effectively calls c.back().
Related Topics
"Volatile" Qualifier and Compiler Reorderings
How to Embed/Link Binary Data into a Windows Module
What Is Namespace Used For, in C++
Wrap Overloaded Function via Std::Function
Fastest Timing Resolution System
C++: Std::Move with Rvalue Reference Is Not Moving Contents
Forward Declaration & Circular Dependency
Stl Container with Std::Unique_Ptr's VS Boost::Ptr_Container
#Error Please Use the /Md Switch for _Afxdll Builds
Mapping Elements in 2D Upper Triangle and Lower Triangle to Linear Structure
How to Write Make_Unique() in VS2012
Opencv Fisheye Calibration Cuts Too Much of the Resulting Image