I want to swap the two values on the top of a std::stack<double>
. Is there a better way than the following to do that ?
void swap_top(std::stack<double>& stack)
{
double a = stack.top();
stack.pop();
double b = stack.top();
stack.pop();
stack.push(a);
stack.push(b);
}
With a plain stack, there's no better way.
Interestingly, the stack
adapter actually exposes the underlying container as a protected member. This means that you can do this:
template <typename T, typename Container = std::deque<T>>
class stack_ex : public std::stack<T, Container> {
public:
using stack_ex::stack::stack;
void swap_top() {
auto last = c.rbegin();
auto before_last = std::prev(last);
std::iter_swap(last, before_last);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With