Queue in C++
The queue adapter follows the First In First Out (FIFO) principle, means the element are inserted at the back and removed from the front of the queue. It is by default implemented using deque container.
The following are the key operations of the queue:
push(elm)
: Inserts the element elm at the back.pop()
: Removes the front element.front()
: Access the front element.back()
: Access the last element.empty()
: Checks whether the queue is empty.size()
: Returns the number of elements in a queue.
Example of Queue
The below example demonstrates the usage of key operations in queue adapter in C++.
C++
// C++ program to demonstrate the usage of key operations in // queue adapter in C++. #include <iostream> #include <queue> using namespace std; int main() { // Create a queue of integers queue< int > myQueue; // Add elements to the queue myQueue.push(10); myQueue.push(20); myQueue.push(30); // Print the size of the queue cout << "Size of queue is: " << myQueue.size() << endl; // Print the elements in the queue cout << "Elements in a queue are: " ; while (!myQueue.empty()) { // Print the front element of the queue cout << myQueue.front() << " " ; // Remove the front element from the queue myQueue.pop(); } return 0; } |
Size of queue is: 3 Elements in a queue are: 10 20 30
Time Complexity: O(n)
Auxilliary Space: O(1)
Container Adapter in C++
The container adapters are a part of the C++ standard library that gives us a way to modify or adapt existing container classes to suit specific needs or requirements. In this article, we will learn about container adapters in C++.