Exchange two values ​​on the stack

I want to change the two values ​​at the top of std::stack<double> . Is there a better way to do this?

 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); } 
+6
source share
6 answers

With a simple stack, there is no better way.

Interestingly, the stack adapter actually provides the underlying container as a protected element. This means 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); } }; 
+11
source

You can do this with smaller stack operations, but using std::swap , although I doubt it will be faster:

 double a = stack.top(); stack.pop(); std::swap(a, stack.top()); stack.push(a); 

Or just don't use stack , use a base container (e.g. deque , vector or list ) directly.

+5
source

This is a fairly standard way of doing this, isolating the "complex" code from the function so that you no longer have to worry about it. Of course, it would be better as a template function, so it is not tied to double -type tables.

Alternatively, you can subclass the stack (the real is-a subclass or the has-a variant) and provide this functionality as optional. But then you still have to write this code, as well as all the code needed to subclass :-)

+2
source

I don't know if this is better, but at least this is an alternative way.

 void swap_top(std::stack<double>& stack) { double a = stack.top(); stack.pop(); swap( a, stack.top() ); stack.push(a); } 
+1
source

No, and I will explain why.

Imagine there is a stack of plates where you can only see the top. The only way you have access to the second plate from the top is to remove the top plate. Now think that you have removed the top plate. The plate, which was previously second from above, is now at the top. How do you modify this plate without first removing it from the stack? This is not possible and therefore you are extracting it. At the moment, the fastest way to swap elements is to simply return them, but in the reverse order in which they were extracted. This is what you have.

0
source

you can take one turn and do it.

Stack: 50 40 30 20 10

put two elements first and insert into the queue β†’ ->

Queue: 50 40 <- deueue 50 and 40 and oush onto the stack, then you get

Stack 40 50 30 20 10

-1
source

Source: https://habr.com/ru/post/985329/


All Articles