VOOZH about

URL: https://www.geeksforgeeks.org/cpp/setbegin-setend-c-stl/

⇱ set::begin() and set::end() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

set::begin() and set::end() in C++ STL

Last Updated : 24 Oct, 2024

In C++, std::set::begin() and std::set::end() are built-in functions used to retrieve set::iterators to the beginning and the end of the set container. Set uses bidirectional iterators, so the iterators returned by these functions support the dereferencing, increment, decrement, relational, and equality operations only.

They are the member functions of the std::set class defined inside <set> header file.

Example:


Output
9
56

You may have noticed we have decremented the set::end() iterator before dereferencing. The reason for this is mentioned below:

set::begin() Method

The std::set::begin() method is used to retrieve a set::iterator pointing to the first element of the std::set container.

Syntax

s.begin();

Parameters

  • This function does not take any parameters.

Return Value

  • Returns an iterator pointing to the first element of the set container.
  • If the set is empty, it returns an iterator equivalent to set::end().

set::end() Method

The std::set::end() is used to retrieve a std::iterator pointing to the theoretical element that is just after the last element of the std::set container. It does not point to the last element, but can by decrementing.

Syntax

s.end()

Parameters

  • This function does not take any parameter.

Return value

  • Returns an iterator pointing to the theoretical element that is just after the last element of the set container.

More Examples of set::begin() and set::end()

Here we will learn how to implement set::begin() and set::end()

Example 1: Iterating a set using set::begin() and set::end()

We can traverse the set by incrementing and dereferencing the set::begin() iterator till it is not equal to the set::end() iterator.


Output
9 11 15 56 

Example 2: Finding Number of Elements in a Set


Output
4

Difference Between set::begin() and set::end()

The following table lists some primary differences between the std::set::begin() and std::set::end() methods:

set::begin()set::end()
Returns an iterator to the first element in the set container.Rturn an iterator to one element after the last element in the set container.

Syntax: s.begin();

Syntax: s.end();

We can dereference set::begin() iterator, because it point to the valid element.

We should not dereference set::end() iterator, because it does not point to valid element.
Comment
Article Tags: