Difference between begin() and cbegin() of Set in C++

This tutorial will discuss the differences between begin() and cbegin() of set in C++.

Table Of Contents

In C++, both begin() and cbegin() are member functions of class set. They both returns an iterator pointing to the first element of the container. However, there’s a subtle difference related to the type of iterator they return and the operations that can be performed using that iterator.

begin() function of Set

  • If set object is non const:
    • For non-const containers, the begin() function returns a mutable iterator (iterator). This means that we can modify the container through this iterator. However, attempting to modify elements of a set through an iterator is not allowed, since elements in a set are const (to preserve the order and uniqueness of elements). So, in the case of set, if we try to modify any element in set using iterator returned by begin() function, then it will return a compilation error.
  • If set object is const:
    • For the const containers, the begin() returns a constant iterator (const_iterator). We can modify any value in container using the const_iterator.

cbegin() function of Set

  • Thecbegin() member function of a container always returns const_iterator, even if container is const or non-const. It always returns a constant iterator (const_iterator). We cannot modify the container or its elements through this const_iterator.

Let’s see the complete example,

#include <iostream>
#include <set>

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

    // Using begin()

    // Get the iterator pointing to first element of Set
    std::set<int>::iterator it = numbers.begin();

    // Error: Elements in a set are constant and can't be modified.
    // *it = 10;  // Error

    // Using cbegin()

    // Get the const_iterator pointing to first element of Set
    std::set<int>::const_iterator cit = numbers.cbegin();

    // Error: Elements in a set are constant and can't be modified
    // *cit = 10;

    return 0;
}

In both cases, if we try to modify the value of a set using iterators, it will give a compilation error.

It is a good habit to use cbegin() and cend() when you don’t intend to modify the container elements, as this makes your intent clear and offers stronger prevention against accidental modifications.

Summary

Today, we learned about difference between begin() and cbegin() of set 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