📜  std::queue - C++ (1)

📅  最后修改于: 2023-12-03 15:20:20.989000             🧑  作者: Mango

std::queue - C++

Introduction

std::queue is a container adapter that provides a queue based on std::deque or std::list containers. It follows the FIFO (First-In, First-Out) data structure, which means that the first element added to the queue is the first one to be removed.

Declaration
template <typename T, typename Container = std::deque<T> >
class queue;

The above declaration is the basic template for std::queue. It takes two template parameters: the first one is the type of elements stored in the queue, and the second one is the underlying container type used to implement the queue. By default, std::deque is used as the underlying container type.

Member Functions
Constructors
  • queue(): Default constructor that creates an empty queue.
  • queue(const queue& other): Copy constructor that creates a copy of the other queue.
  • queue(queue&& other): Move constructor that moves the contents of other into a new queue.
  • explicit queue(const Container& cont): Constructs a new queue from a copy of cont.
Element Access
  • T& front(): Returns a reference to the first element in the queue.
  • const T& front() const: Returns a const reference to the first element in the queue.
Capacity
  • bool empty() const: Returns true if the queue is empty, false otherwise.
  • size_t size() const: Returns the number of elements in the queue.
Modifiers
  • void push(const T& value): Inserts an element value at the back of the queue.
  • void push(T&& value): Inserts an element value at the back of the queue using move semantics.
  • void pop(): Removes the first element from the queue.
  • void swap(queue& other): Swaps the contents of the queue with other.
Example
#include <iostream>
#include <queue>

int main() {
  std::queue<int> q;
  q.push(1);
  q.push(2);
  q.push(3);

  std::cout << "Front of the queue: " << q.front() << std::endl;
  std::cout << "Size of the queue: " << q.size() << std::endl;

  q.pop();
  std::cout << "After popping one element:" << std::endl;
  std::cout << "Front of the queue: " << q.front() << std::endl;
  std::cout << "Size of the queue: " << q.size() << std::endl;

  return 0;
}

Output:

Front of the queue: 1
Size of the queue: 3
After popping one element:
Front of the queue: 2
Size of the queue: 2
Conclusion

std::queue provides a convenient way to implement a FIFO data structure using a std::deque or std::list container. Its member functions are similar to those of std::deque, but it offers additional functionalities such as push and pop. It is a useful container adapter to use in many different scenarios.