C++ std::queue example using STL

C++ std::queue example – Program will include example of functions queue push , front, pop and size. Queue stores data in FIFO ( First in first out manner). Elements in the queue are inserted from end using push() function and deleted form front using pop() function of the queue.

 

Header file required : “#include <queue>” . Brief description of functions  before queue C++ example.

 

std::queue::push( element to insert ) – Adds elements at the end of the queue.
empty() – Returns whether the queue is empty
std::queue::size() – Returns the size of the queue
std::queue::front() – Returns first element of the queue, but does not delete
std::queue::back() – Returns last element of the queue but does not delete
std::queue::pop() – Deletes the first element of the queue from front

 

C++ std::queue example program with its functions


/*
* STL - std::queue example functions C++
*/

#include <string>
#include <queue>
#include <iostream>
using namespace std;

int main()
{ 
 queue<string> Q;
 
 /*
 *std::queue:push example
 */
 Q.push("Apple");
 Q.push("Mango");
 Q.push("Banana");
 Q.push("Kiwi");
 Q.push("Berry");


 /*
 *std::queue:size example
 */
 cout<< "Queue size: "<<Q.size()<<endl;



/*------------------------------
 *std::queue:front example
 */

if(!Q.empty()){
 cout<<"Front element: "<<Q.front().c_str()<<endl;
 }

/*------------------------------
 *std::queue:pop example
 */

if(!Q.empty()){
 Q.pop();
 cout<<"Front element after 1 pop : ";
 cout<<Q.front().c_str()<<endl;
 }

/*------------------------------
 *Iterate through all the queue
 * print fron element and remove it
 *from the queue using pop function
 */

cout<<"Remaining elements in Queue: "<<endl;
 while(!Q.empty()) {
 //print front element
 cout <<Q.front() << "\n";
 //Pop elements from the queue
 Q.pop();
 }

return 0;
}

 

Output:
Queue size: 5
Front element is : Apple
Front element after one pop operation : Mango
Remaining elements in Queue:
Mango
Banana
Kiwi
Berry