Set end() function in C++

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

Table Of Contents

In C++, the set container from the Standard Template Library (STL) provides a way to store unique elements in a sorted sequence. To traverse or iterate over these elements, set provides the end() function which is crucial for defining the limit of the set during iteration.

Syntax od set::end()

iterator end() noexcept;

Parameters: None.

Return Value:
– Iterator pointing just past the last element in the set.

The set class provides a function named end() which returns an iterator that refers to the “past-the-end” element of the set. The term “past-the-end” refers to a position just after the last element in the set, essentially marking the set’s end.

The iterator returned by the end() function is commonly used in tandem with the begin() function. The begin() function returns an iterator pointing to the set’s first element. We can increment this iterator until it matches the “past-the-end” iterator returned by the end() function. This allows us to iterate over all elements in the set.

Example of set::end()

Let’s look at an example that demonstrates the use of the iterator returned by the end() function.

Let’s see the complete example,

#include <iostream>
#include <set>

int main()
{
    std::set<int> numbers = {11, 22, 33, 44, 55};

    // Iterate over the Set elements using iterators
    // returned by begin() and end() functions
    for(std::set<int>::iterator it = numbers.begin();
        it != numbers.end();
        it++)
    {
        std::cout << *it << " ";
    }
    std::cout<< std::endl;

    return 0;
}

Output

11 22 33 44 55

Scenarios for Exceptions and Undefined Behavior

  1. Dereferencing End Iterators: The iterators returned by end() function point to a position just after the last element in the set. Dereferencing such iterators leads to undefined behavior. Always ensure that you don’t attempt to access the value pointed to by an end iterator.

  2. Iterator Invalidation: Operations like erase() may invalidate iterators. Using an invalidated iterator, especially in conjunction with end(), can cause undefined behavior.

  3. Thread Safety: using end() function concurrently in multiple threads can introduce race conditions. If one thread modifies the set (like inserting or erasing elements) while another thread is accessing its end, it may lead to undefined behavior. Proper synchronization is needed when accessing the set concurrently from multiple threads.

Summary

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

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