No need for recursion, this would be a useless waste of resources. No need to mutate your queue
and stack
either (in other words, this works even on const
's).
Assuming your std::stack
and std::queue
both internally use the same type of underlying container (which should be std::dequeue
if you used the default) then you can access the protected members c
(your real containers) of both queue
and stack
and compare them using operator ==
:
#include <iostream>
#include <queue>
#include <stack>
template<typename Adapter>
typename Adapter::container_type const& getContainer(const Adapter& adapter) {
struct AccessProtected : private Adapter {
static typename Adapter::container_type const& getContainer(const Adapter& adapter) { return adapter.*&AccessProtected::c; }
};
return AccessProtected::getContainer(adapter);
}
int main() {
std::queue<int> queue;
std::stack<int> stack;
for (int i = 0; i < 10; ++i) {
queue.push(i);
stack.push(i);
}
std::cout << (getContainer(queue) == getContainer(stack) ? "equal" : "not equal") << std::endl;
return 0;
}
Now, if you use different containers types as the underlying implementation of queue
and stack
, you can still use that same getContainer()
technique to obtain containers that are sorted in the same order: both queue::push()
and stack::push()
call the underlying container's push_back()
method, it's only when you pop()
(and similar operations) that the reversing happens for stack
. Since those underlying containers will be in the same order, you can then compare things more easily (left as an exercise to the reader ;)).
Credit: I was too lazy to reimplement a protected member accessor again, so I shamelessly copied and modified this one.