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; }
Output
First element in the set: 5
Scenarios for Exceptions and Undefined Behavior
-
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.
-
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.
-
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.
-
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.
Pointers in C/C++ [Full Course]
Frequently Asked:
Summary
Today, we learned about set cbegin() function in C++ stl.