≡ Menu

How to Use C++ STL Queue with an Example Program

If you stand in a queue at a grocery store (or anywhere else), the first customer in the queue will be served, and then the next, and so on.

In programming terminology, especially in data structure, this concept is called FIFO (first in first out) queue.

In C++, Queue is an important part of a STL (Standard Template Library).

Apart from the typical FIFO queue, there are few other types of queue. For example, priority queue.

In a priority queue, apart from the FIFO characteristics, certain customers (or elements in a queue) might have a higher priority, and they might receive immediate service irrespective of their location in the queue.

In this tutorial, we’ll discuss the following aspects of STL Queue:

  • Create a Queue
  • Check Queue Status
  • Access Next Element
  • Access Last Element
  • Add New Element to the Queue
  • Create and Insert Element to the Queue
  • Remove Element from the Queue
  • Swap the Content of an Element

If you are new to C++ STL concept, the following might help:

The following are few important functions/statements required to create your queue program:

  • #include <queue>- In order to use STL queue, add this include. This will include some important files to the code we are writing.
  • queue <type> ourQueue; – Declare queue of some type
  • ourQueue.empty(); – Check if the queue is empty. If queue is empty the answer will be true, otherwise the answer is false.
  • ourQueue.size(); – Figure out the number of elements in your queue. Just like size, you also have sizeof() operation as well.
  • ourQueue.front() and ourQueue.back(); – You can access the first element in the queue, or the last element in the queue using front and back function respectively.
  • ourQueue.push(); – When you are creating the queue, you can use push to add new elements to the queue.
  • ourQueue.pop(); – If you would like to remove the element from the queue, use the pop function:
  • You also have emplace and swap. Emplace is used to construct and insert element into the queue. Swap is used when you need to swap the content. The syntax for these two functions are similar to the above functions.

STL Queue Basic Example Code

Our task is to create a queue and add some elements( 3, 6 and 7) to it. After that, we’ll remove the elements from the queue.

In order to make it more simple I will use one ciphered numbers, and there will be few public member functions applied.

#include <iostream>
#include <queue>

using namespace std;

int
main( void )
{

queue < int > ourQueue;

cout<<"The occupied place in the memory is = "
       <<ourQueue.size()
       <<endl;

ourQueue.emplace( 3 );
ourQueue.emplace( 6 );
ourQueue.emplace( 7 );


cout<<"The occupied place in the memory is = "
       <<ourQueue.size()
       <<endl
       <<"And with the bits it is ="
       <<ourQueue.size() * sizeof( int )
       <<endl;


while( ! ourQueue.empty() )
{
     int iTemp = ourQueue.front();
     cout<<iTemp<<endl;
     ourQueue.pop();
}

return EXIT_SUCCESS;
}

In general, in the above code we did the following:

  • Create a queue
  • Calculate the size of the queue before any elements were added
  • Construct and insert few elements,
  • Calculate the size after the elements were added
  • Empty the content of the queue

The following are few suggestions to improve the above basic code:

1) First, probably you can add some meaningful comments in the above program to explain what it does.

2) Second, add few lines of code to understand how front and pop works.

Probably you can add the following line to the above sample code, after you have emplaced those elements into our queue.

int iTempFront = ourQueue.front();
cout<<iTempFront;

After that add one more time the same two lines of code. Now, use method pop in between those added lines of code, something like this:

int iTempFront = ourQueue.front();
cout<<iTempFront;

ourQueue.pop();

iTempFront = ourQueue.front();
cout<<iTempFront;

3) Third, add few lines of code to understand how back works. Replace the above few lines of code with the following.

int iTempFront = ourQueue.back();
cout<<iTempFront;

ourQueue.pop();

iTempFront = ourQueue.back();
cout<<iTempFront;

So, now you understand the back member function and you should be able to figure out what is difference between front and back, as well as why pop is used for.

4) Fourth, remove those three emplace member functions and replace that part of the code with this one:

do
{
  char cChoice;
  cout<<" More elements (y)es / (n)o ->";
  cin>>cChoice;
  
  if( ( cChoice == 'N' ) || ( cChoice == 'n') ) { break;}
 else  if( ( cChoice == 'Y' ) || ( cChoice == 'y'))
  {
      int iNextOne;
      cout<<"Next element->";
      cin>>iNexOne;
      ourQueue.push( iNexOne);
  }
  else
 {
    cout<<"Wrong choice!!!";
    systm("clear");
 }
 
}
while( 1 );

Additional Thoughts on Queue

Now that you have some basic idea about queue, you should also understand the following two types of queues that you might encounter.

  • Limited Queue – Limited queue is implemented with simple array. This implementation is mostly not interesting and it is more useful in C.
  • Unlimited Queue – This uses struct(class) and pointers. While practically there is no limit to this, it is limited by the physical resources you have on your system.

When you start creating serious programs in C++, you could have queue of objects or you might have queue of something in your class.

In the world of C, deciding when to use queue over array is simple. If you don’t know how many objects you will need to store, the array was not useful. Now, there are vectors and you could add elements at the end of it and even swap them.

Two most basic dynamic data structures are: stack and queue. They are similar. Stack will return last added element. On the other hand, queue will return first added element. So, if you add elements on one side and later remove them from your particular container, those two data structures could be good pick.

If you need to add elements at the beginning and at the end of structure deque might be considered. This could be reason why to pick deque over the vector. However, if you need to add elements in the middle of our data structure, you might be needing list. Bad side of list could be felt in situations when you need to access first, second, third or n-th element of the list. In order to improve original list you could deploy few tricks.

Additional Queue Exercises

  1. Create the queue that will store active processes one your computer. It would be good idea to type ps aux into terminal and figure what you might need.
  2. Create a queue for music playlist. Your task is to create part of the code that will store names of song, locations on the disk, and few additional information about the song.
  3. Create two queues, one will have grater priority and the second one will have lower priority. The strategy of consuming elements from those queues it this: if queue with greater priority is not empty take element from that queue, and if the queue with higher priority is empty get elements from the queue with lower priority.
  4. Same as above #3, but use the stack for lower priority data structure.
  5. Your task is to crate the part of the program that will store messages to be encrypted.
  6. Create the page, it will have sentences of one conversation. Those sentences will be kept as the stings and added from the file. After you have completed reading from the file, display these sentences on the screen. Try to limit the size of the queue, so that your program won’t crash.
  7. Create a program to manage printer queue.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Joseph Mwangi May 12, 2017, 12:11 am

    i like it and it of much help to me.
    please would you answer me question 2, 3, 6.
    i tried but i couldn’t.