Queue
Lesson 11 of 23 in Coddy's C++ - Standard Template Library course.
The C++ Queue is a data structure that provides us the functionality of a queue, more precisely, it follows the FIFO (First in-First out) principle. This means that the elements that are added first to the queue, will exit the queue, or they will be removed from the queue first.

queue<dataType> queueName;In order to create a queue in C++, we need to include the queue header file at the top of the C++ file using #include <queue>.
We can now declare a queue in our program as follows:
queue<int> queueOfNums;We need to learn how we add new elements to the queue. We do that using the push() method. The push() method inserts a new element at the end of the queue.
queueOfNums.push(1);
queueOfNums.push(2);
...Next, we want to display the elements of the queue. Because it is a queue, we can display the first element that was added to the queue. For that, we use the front() method. It returns the first element of the queue.
cout << queueOfNums.front();Output:
1Unlike the stack, where we are only able to output the top element, or the last element of the stack. With the queue, we can output the last value of the queue as well. We do that using the back() method, it returns the last element of the queue.
queueOfNums.push(3);
cout << queueOfNums.back();Output:
3We also need to learn how we remove the elements from the queue. Unfortunately, we can only remove the element that is on the front and was added first, because it is still a queue, so we can't remove the last element first, we use the stack for that and the LIFO (Last in-First out) principle.
So, we remove the element on the front using the pop() method.
queueOfNums.pop();
cout << queueOfNums.front() << endl;
queueOfNums.pop();
cout << queueOfNums.front();Output:
1
2Queue Methods
| Method | Functionality |
size() | Returns the number of elements in the queue |
empty() | Returns true if the queue is empty, false otherwise |
swap() | Swaps the contents of one queue, with another |
Challenge
EasyGiven 10 numbers from input. Use a queue and output the numbers by removing them one by one and outputting only the even ones.
Input
1 2 3 4 5 6 7 8 9 10Output
2 4 6 8 10Try it yourself
#include <queue>
#include <iostream>
using namespace std;
int main()
{
// Enter your code here
return 0;
}