Queue in STL | C++

/Queue in STL | C++

The queue container is used to replicate queue in C++, insertion always takes place at the back of the queue and deletion is always performed at the front of the queue.

queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the “back” of the specific container and popped from its “front”. The standard container classes deque is used for Queue.

Member Functions

  • reference& back();
    const_reference& back() const;
    Returns a reference to the last element in the queue. This is the “newest” element in the queue (i.e. the last element pushed into the queue).
  • bool empty() const;
    Returns whether the queue is empty: i.e. whether its size is zero.
  • reference& front();
    const_reference& front() const;
    Returns a reference to the next element in the queue.
  • void pop();
    Removes the next element in the queue, effectively reducing its size by one.
  • void push (const value_type& val);
    void push (value_type&& val);
    Inserts a new element at the end of the queue, after its current last element. The content of this new element is initialized to val.
  • void swap (queue& x) noexcept
    Exchanges the contents of the container adaptor (*this) by those of x.

 

Example

#include <iostream>
#include <queue>

int main ()
{
  std::queue<int> myqueue;
  int sum = 0;

  myqueue.push(12);
  myqueue.push(75);

  // Updating back element
  myqueue.back() -= myqueue.front();

  // Traverse the queue untill it is empty
  while (!myqueue.empty())
  {
    sum += myqueue.front();
    myqueue.pop();
  }
  
  // Swap queue
  std::queue<int> foo,bar;
  foo.push (10); foo.push(20); foo.push(30);
  bar.push (111); bar.push(222);

  foo.swap(bar);
  
  return 0;
}

 

September 18th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of