6

Set size() function in C++ STL

 9 months ago
source link: https://thispointer.com/set-size-function-in-c-stl/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

Table Of Contents

Advertisements

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

Copy to clipboard
<code class="language-cpp">size_type size() const noexcept;
</code>
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,

Copy to clipboard
#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;
#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

Copy to clipboard
Number of Elements in set: 3
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK