Set size() function in C++ STL

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

Table Of Contents

The C++ set container, which is a part of the Standard Template Library (STL), is designed to store unique elements in a sorted sequence. The size() member function can be used to retrieve the number of elements present in the Set.

Syntax of set::size() function

size_type size() const noexcept;

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

Return Value:
– Returns the number of elements in the set. The type returned is size_type, which is an unsigned integral type.

The set class offers the size() function that returns the number of elements contained within the set. For instance, if we add three elements to the set and then call the size function, it will return 3. The return value’s type is size_t.

Example of set::size()

Let’s see the complete example,

#include <iostream>
#include <set>

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

    // Add elements to Set
    numbers.insert(10);
    numbers.insert(11);
    numbers.insert(12);

    // Get number of elements in Set
    size_t count = numbers.size();

    std::cout << "Number of Elements in set: " << count << "n";

    return 0;
}

Output

Number of Elements in set: 3

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

  1. Thread Safety Concerns: If a set is being accessed concurrently by multiple threads, and one thread is reading the size while another is modifying the set (e.g., adding or erasing elements), this might lead to race conditions. Ensure to synchronize access to the set in multi-threaded scenarios to maintain data integrity and consistency.

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

Summary

Today, we learned about set size() 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