Set cbegin() function in C++ STL

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

Table Of Contents

In the C++ Standard Template Library (STL), the set is a container that stores unique elements in a specific order. One of its fundamental member functions is begin(), which provides an iterator pointing to the first element in the set.

Syntax of set::cbegin()

const_iterator cbegin() const noexcept;

This function returns returns a constant iterator pointing to the first element in the set. Being a constant iterator, neither the position it points to nor the element’s value can be modified.

Parameters of set::cbegin()

- None

Return Value of set::cbegin()

  • A Constant Iterator pointing to the first element in the set.

Example of set::cbegin()

Let’s see the complete example,

#include <iostream>
#include <set>

int main()
    std::set<int> numbers = {5, 15, 25, 35, 45};

    std::set<int>::const_iterator it = numbers.cbegin();

    std::cout << "First element in the set: " << *it << "n";

    return 0;


First element in the set: 5

Scenarios for Exceptions and Undefined Behavior

  1. Iterator Invalidation:

    • If the set is modified in such a way that the structure changes (like after an set::erase() operation), previously acquired iterators through cbegin() function or any other function, might get invalidated. Using such iterators can result in undefined behavior.
  2. Dereferencing End Iterators:

    • If set is empty then the cbegin() function would return an iterator equivalent to cend(). Dereferencing such an iterator is undefined behavior.
  3. Modifying Elements:

    • The value of elements in a set is immutable. Also, if you try to modify the set contents using a constant iterator acquired via cbegin(), it will result in a compile-time error.
  4. Thread Safety:

    • Concurrent access by multiple threads can lead to race conditions. I

Using cbegin() with cend()

The cbegin() function of the set container is fundamental for iterative access, often used in combination with cend() to iterate over the entire set for read-only access.


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