C++ empty()

moray581's avatar
Published Aug 20, 2025
Contribute to Docs

In C++, the empty() method for std::set determines whether the set contains no elements. It returns true if the container is empty and false otherwise.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

set_name.empty()

Parameters:

This method does not take any parameters.

Return Values:

Returns true if the container is empty and false otherwise.

Example: Using empty() with std::set

The code below demonstrates how to use the empty() method with std::set in C++, printing a message based on whether the set is empty or not:

#include <iostream>
#include <set>
int main()
{
std::set<int> my_set;
if (my_set.empty())
std::cout << "Set is empty\n";
else
std::cout << "Set has elements\n";
std::set<int> my_other_set{2, 4, 3};
if (my_other_set.empty())
std::cout << "Set is empty\n";
else
std::cout << "Set has elements\n";
return 0;
}

The output of the above code is:

Set is empty
Set has elements

Codebyte Example: Using empty() to Calculate a Sum

In this example, the empty() method helps control a loop that sums and removes elements until the set becomes empty:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours