C++ - STL (Standard Template Library) - Using the queue container

We are going to see in this queue tutorial, how to use it.

Let's see it with this first snippet.
In the easy example below, we add 10 elements in the queue before displaying its content.
We have to notice that we cannot iterate through a queue.

So we have to use the couple queue.front() and queue.pop() to loop inside the queue.

#include <queue>

#include <iostream>


int main()

{

std::queue<int> myQueue;

int i;


i = 0;

while (i < 10)

myQueue.push(i++);


std::cout << "Size of the queue: " << myQueue.size() << std::endl;

std::cout << "First element of the queue: " << myQueue.front() << std::endl;

std::cout << "Last element of the queue: " << myQueue.back() << std::endl;

while (!myQueue.empty())

{

std::cout << myQueue.front() << std::endl;

myQueue.pop();

}

return 0;

}
Result:
 
Size of the queue: 10

First element of the queue: 0

Last element of the queue: 9

0

1

2

3

4

5

6

7

8

9
 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.