Introduction to Queues and std::queue

Checking Queue Size: empty() vs size()

When should I use the empty() method instead of comparing the size() to 0 to check if a queue is empty?

Vector art representing computer hardware

Both empty() and comparing size() to 0 can be used to check if a queue is empty, but there are some differences to consider:

  1. Readability: Using empty() makes the code more readable and expressive. It clearly conveys the intention of checking if the queue is empty, whereas comparing size() to 0 might not be as intuitive at first glance.
  2. Performance: In most implementations, empty() is a constant-time operation, meaning it takes the same amount of time regardless of the queue's size. On the other hand, size() might take linear time in some implementations, especially for certain underlying containers. However, in practice, the performance difference is often negligible for small to medium-sized queues.

It's generally recommended to use empty() when you simply want to check if the queue is empty, as it improves code readability without sacrificing performance. Here's an example:

#include <iostream>
#include <queue>

int main() {
  std::queue<int> myQueue;

  if (myQueue.empty()) {
    std::cout << "The queue is empty.\n";
  } else {
    std::cout << "The queue is not empty.\n";
  }
}
The queue is empty.

However, if you need to know the actual size of the queue for other purposes, such as comparing it to a specific value or performing calculations based on the size, then using size() is more appropriate:

#include <iostream>
#include <queue>

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

  if (myQueue.size() > 2) {
    std::cout << "The queue has more than"
      " 2 elements.\n";
  } else {
    std::cout << "The queue has 2 or fewer"
      " elements.\n";
  }
}
The queue has more than 2 elements.

In summary, use empty() when you only need to check if the queue is empty, and use size() when you need to know the actual size of the queue for other purposes.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved