Set cend() function in C++

This tutorial will discuss about the set cend() 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 cend() function which is crucial for defining the limit of the set during iteration.

Syntax od set::cend()

const_iterator cend() const noexcept;

Parameters: None.

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

The set class provides a function named cend() which returns a constant 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 constant iterator returned by the cend() function is commonly used in tandem with the cbegin() function. The cbegin() function returns a constant iterator pointing to the set’s first element. We can increment this iterator until it matches the “past-the-end” iterator returned by the cend() function. This allows us to iterate over all elements in the set.

Example of set::cend()

Let’s look at an example that demonstrates the use of the iterator returned by the cend() 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 cbegin() and cend() functions
    for(std::set<int>::const_iterator it = numbers.cbegin();
        it != numbers.cend();
        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 cend() 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 cend(), can cause undefined behavior.

  3. Thread Safety: using cend() 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 cend() 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