Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two values on a stack

Tags:

c++

stack

swap

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);
}
like image 969
Caduchon Avatar asked Apr 17 '15 08:04

Caduchon


1 Answers

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);
  }
};
like image 168
Sebastian Redl Avatar answered Oct 12 '22 05:10

Sebastian Redl