The main difference between a queue and a stack lies in the order in which elements are added and removed:
In C++, the standard library provides the std::queue
class template for queues and the std::stack
class template for stacks. Both are container adaptors, meaning they use an underlying container to store the elements.
Here's an example illustrating the difference between a queue and a stack:
#include <iostream>
#include <queue>
#include <stack>
int main() {
std::queue<int> myQueue;
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
std::stack<int> myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
// Output: 1
std::cout << "Queue front: "
<< myQueue.front() << std::endl;
// Output: 3
std::cout << "Stack top: "
<< myStack.top() << std::endl;
}
Queue front: 1
Stack top: 3
In this example, the first element added to the queue (1
) is the first one to be accessed using myQueue.front()
, while the last element added to the stack (3
) is the first one to be accessed using myStack.top()
.
Answers to questions are automatically generated and may not have been reviewed.
std::queue
Learn the fundamentals and applications of queues with the std::queue
container.