queue in c++
To implement a queue in C++, you can use the built-in container class std::queue
from the Standard Template Library (STL). Here are the steps to create and use a queue in C++:
- Include the necessary header file:
cpp
#include <queue>
- Declare a queue object:
cpp
std::queue<int> myQueue;
In this example, we declare a queue named myQueue
that can store integers. You can replace int
with any other data type you want to use.
- Push elements into the queue:
cpp
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
This code snippet adds elements 10
, 20
, and 30
to the queue using the push()
function.
- Check the front element of the queue:
cpp
int frontElement = myQueue.front();
The front()
function returns the value of the front element of the queue, which is 10
in this case.
- Check the size of the queue:
cpp
int queueSize = myQueue.size();
The size()
function returns the number of elements currently present in the queue, which is 3
in this case.
- Check if the queue is empty:
cpp
bool isEmpty = myQueue.empty();
The empty()
function returns true
if the queue is empty, and false
otherwise.
- Pop elements from the queue:
cpp
myQueue.pop();
The pop()
function removes the front element from the queue.
These are the basic steps to create and use a queue in C++ using the std::queue
class from the STL. Remember to include the necessary header file, declare the queue object, use the appropriate functions to push, access, and remove elements, and check the size and emptiness of the queue as needed.