Reputation: 375
This is my first attempt at creating a queue using two stacks. I am not sure if I am on the right track because I have been unable to check my work due to an '=': cannot convert from 'void' to 'int'
error. The error lies on this line: x = enQ.pop();
. enQ is not a function, so how could it be void?
My code is not yet finished of course.
stack<int> enQ;
stack<int> deQ;
void enQueue(int x) {
enQ.push(x);
cout << x << " has been added to the queue." << endl;
}
void deQueue() {
while (enQ.size() != 0) {
int x;
x = enQ.pop();
enQ.pop();
deQ.push(x);
cout << x << " had been pushed to DEQUEUE" << endl;
}
}
Upvotes: 2
Views: 239
Reputation: 3614
You can check this post to see why STL separate the T kind_of_pop_and_get()
into pop
and top
. Former only removes the top element on stack, and latter simply copying the top element without touching stack.
Why doesn't std::queue::pop return value.?
In short, it is for exception safety.
The kind_of_pop_and_get()
will do
copy assignment/constructor
of receiver. Exception may throw during object construction and start the stack unwinding. Then the stack state could be affected even the kind_of_pop_and_get()
call is not completed.
Upvotes: 1
Reputation: 172994
Because the function std::stack::pop returns nothing (i.e. its return type is void
).
You could change
x = enQ.pop();
to
x = enQ.top();
enQ.pop();
Upvotes: 1