C++17 STL Cookbook
上QQ阅读APP看书,第一时间看更新

Stack handling

We push items onto the stack, simply using the push function of std::stack:

val_stack.push(val);

Popping values from it looks a bit more complicated because we implemented a lambda for that, which captures a reference to the val_stack object. Let's look at the same code, enhanced with some more comments:

auto pop_stack ([&](){
auto r (val_stack.top()); // Get top value copy
val_stack.pop(); // Throw away top value
return r; // Return copy
});

This lambda is necessary to get the top value of the stack and remove it from there in one step. The interface of std::stack is not designed in a way which would allow doing that in a single call. However, defining a lambda is quick and easy, so we can now get values like this:

double top_value {pop_stack()};