Store results of std::stack .pop() method into a v

2019-01-14 15:41发布

I'd like to do the following:

std::stack <int> s;
int h = 0;
s.push(2);
h = s.pop();

Such as to have h hold the value 2. When I try my method, I get “void value not ignored as it ought to be”.

Is this not the intention of the .pop() method? What is the preferred way to do this?

标签: c++ stack
4条回答
贪生不怕死
2楼-- · 2019-01-14 16:22

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.)

查看更多
对你真心纯属浪费
3楼-- · 2019-01-14 16:22

You can actually use s.top() to store the element and then pop it using

s.pop().

use

int h=s.top();
s.pop()

instead of

int h=s.pop()

You cannot directly assign s.pop() to some data type, as s.pop() removes element from stack and returns nothing.

查看更多
Lonely孤独者°
4楼-- · 2019-01-14 16:35

S.pop() does not return any value. Because pop() is void function. If you want to see the top of the stack then it will be S.top(). If you store this value then write value = S.top().

查看更多
够拽才男人
5楼-- · 2019-01-14 16:47

You can use:

h = s.top();

then after that use(if you want to remove the most recent value otherwise do nothing)

 s.pop();

It works the same way!!

查看更多
登录 后发表回答