C++ empty()
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.
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";elsestd::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";elsestd::cout << "Set has elements\n";return 0;}
The output of the above code is:
Set is emptySet 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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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