user14049652
user14049652

Reputation:

Stack combine both pop() and top()?

With a std::stack we use pop() to extract last member and top() to get its value. Is there any shortcut to do both actions together (Get value of last member and kick it out)?

Upvotes: 1

Views: 2470

Answers (4)

Pete Becker
Pete Becker

Reputation: 76370

The reason that pop() does not return the value of the popped element is that doing that is not exception-safe. If the copy constructor for the returned value throws an exception the value has been lost. It’s been removed from the stack but it hasn’t been copied. There’s no way to get it back. If you don’t care about that, you can write your “shortcut” function in the obvious way: copy the top() object, pop() the stack, and return the value.

Upvotes: 6

cdhowie
cdhowie

Reputation: 169123

There is no technical reason that this couldn't be done. It can be implemented simply enough as a utility:

template <typename T>
auto pop_value(T & stack) {
    auto v = std::move(stack.top());
    stack.pop();
    return v;
}

If using C++11 where return type deduction is not available, replace auto with typename T::value_type.

Upvotes: 4

eerorika
eerorika

Reputation: 238381

Is there any shortcut to do both actions together

No.

But you can write a function that calls both and use it as your "shortcut".

Upvotes: 2

rootkonda
rootkonda

Reputation: 1743

top() - only returns the element but doesn't remove it. pop() - only removes the element but doesn't return anything.

There is no such method where it remove and return the removed element.

Make sure to do an empty check when doing top or pop as it causes error. Please have empty check before doing any of these actions.

Upvotes: 1

Related Questions