Set empty() function in C++ STL

This tutorial will discuss about the set empty() function in C++ stl.

Table Of Contents

In the C++ Standard Template Library (STL), the set is a container that ensures a collection of unique elements in a sorted order. The empty() function within the set container helps determine whether the set is empty, i.e., it contains no elements.

Syntax of set::empty() function

bool empty() const noexcept;

Parameters:
– None. The function doesn’t take any parameters.

Return Value:
– Returns true if the set contains no elements.
– Returns false otherwise.

The set class provides a function named empty(), which returns true if the size of the set is zero, indicating the set is empty. If the set contains one or more elements, it will return false, because the set is not empty. This function can be used to determine whether a set is empty or not. Let’s examine a complete example.

Example of set::empty()

Let’s see the complete example,

#include <iostream>
#include <set>

int main()
{
    std::set<int> numbers;

    // Check if Set is empty
    if (numbers.empty())
    {
        std::cout << "Yes, Set is Empty n";
    }
    else
    {
        std::cout << "No, Set is not Empty n";
    }

    // Add element to Set
    numbers.insert(10);

    // Check if Set is empty
    if (numbers.empty())
    {
        std::cout << "Yes, Set is Empty n";
    }
    else
    {
        std::cout << "No, Set is not Empty n";
    }

    return 0;
}

Output

Yes, Set is Empty 
No, Set is not Empty

Scenarios for Exceptions and Undefined Behavior with set::empty()

  1. Thread Safety Concerns: If a set is being accessed from multiple threads simultaneously, and one of them is invoking the empty() function while another is adding or removing elements, this can lead to race conditions. It’s essential to synchronize multi-threaded access to the set using suitable primitives, such as mutexes, to prevent such scenarios.

  2. Using After Free: If a set object has been deleted (either by going out of scope or being explicitly deleted) and you attempt to call the empty() function on it, this will lead to undefined behavior.

Summary

Today, we learned about set empty() function in C++ stl.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top