All about queue STL in c++ for competitive programming( initialization, traversal and methods/functions ) :
queue STL
Important Points:
- It is a type of container adaptor which follows FIFO (First In First Out) rule.
- Elements are pushed from the back of the container and are extracted from its front.
- It is same as the queue in c but with a huge advantage of availability of direct functions/methods for many operations.
- Remember to use the header file #include<queue> before using queue STL.
How do i remember FIFO ?
- Assume a queue (line) of people in front of a ticket counter.
- Now think of the people as elements and the room as the container (ignore the ticket counter).
- A person exits the queue from the front.
- A new person can only enter the queue from the last.
- A person can only exit the queue only if the people in front of it exits the queue first which means FIFO (First in First out) i.e the person who entered the queue first can only exit the queue first.
deque vs queue:
- In
queue insertion takes place from one end and removal takes place at the
other end while in deque insertion/removal can be done from any end.
- We can use iterators with deque but not with queue.
queue STL initialization
declaring a queue and using push( ) method to put elements into it from back:
queue < int > q ;
q.push( 10 ) ;
q.push( 20 ) ;
q.push( 30 ) ;
q.push( 10 ) ;
q.push( 20 ) ;
q.push( 30 ) ;
Therefore,
dq = { 10, 20, 30 }
All queue STL methods/ functions
queue STL important functions:
3. empty( ) : returns true if the container is empty otherwise, false.
4. front( ) : returns the top first/front element of the queue.
6. pop( ) : removes the front/first element of the queue.
7. swap( ) : used to exchange the content of two queue containers of same type (size may differ).
emplace( ) vs push( ) which to use?
- emplace() avoids unnecessary copy of objects.
- for primitive data types it does not matter which one to use but for objects or bigger objects use emplace() for efficiency.
- unlike push(), no copy or move operation are performed in emplace().
all queue STL important functions with example
1. Initializing queue : queue< int > q ;
2. Putting elements into it :
q.push( 10 ) ;
q.push( 30 ) ;
q.push( 20 ) ;
Therefore,
q = { 10, 30, 20 }
3. cout << q.size( ) ; // 3
4. cout << q.front( ) ; //10
5. cout << q.back( ) ; // 20
6. Checking whether queue is empty or not :
if( q.empty( ) = = false )
cout << "not empty" ; //it will be printed
else
cout << "empty" ;
9. q.pop( ) ;
// front element removed i.e 10
queue STL traversal method
Let our queue be q :
queue < int > q ;
while ( !q.empty( ) )
{
cout << q.front( ) << " ";
q.pop( );
}
Comments
Post a Comment