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


Reading time: 20 minutes | Coding time: 5 minutes

Set is a data structure that stores elements. It is a simple yet effective data structure when used correctly. In C++'s Standard Template library (STL), we have set as a container that is used to store the values which are unique i.e no value in a set can be repeated or edited. If you want to edit the value added by you the only way is to remove the wrong element and add the correct one.

To understand begin and end function of set, let us revisit the concept of iterators and bidirectional iterators:

  • Iterator in C++ is an object that points to an element in a container. It can be used to traverse elements in the container (such as set, linked list and others).

There are different types of iterators which different functionalities one of which is bidirectional iterators.

  • Bidirectional iterators are iterators that can be used to access elements in a container in both direction that is forward and backwards.

set::begin()

begin() function is used to return an iterator pointing to the first element of the set.

Syntax:

setname.begin()
  • Parameters : No parameters are passed.
  • Returns : This function returns a bidirectional iterator pointing to the first element of the set

set:: end()

It returns an iterator pointing to the last element of the set. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator.

Syntax :

setname.end()
  • Parameters : No parameters are passed.
  • Returns : This function returns a bidirectional iterator pointing to next of the last element.

Example 1: Traverse integer set in order

In this example, we will use begin and end to traverse the set from the first element to the last element and print all elements in order. The set has integer values.

#include <iostream> 
#include <set> 
using namespace std;  
int main() 
{ 
    set<int> myset{1, 2, 3, 4, 5}; 
    for (auto it=myset.begin(); it != myset.end(); it++) 
        cout << ' ' << *it; 
    return 0; 
} 
Output :
1 2 3 4 5

Example 2: Traverse in reverse order

In this example, we will use begin and end to traverse the set from the last element to the first element and print all elements in reverse order. The set has integer values.

#include <iostream> 
#include <set> 
using namespace std;  
int main() 
{ 
    set<int> myset{1, 2, 3, 4, 5}; 
    auto it=myset.end();
    for (it--; it != myset.begin(); it--) 
        cout << ' ' << *it; 
    cout << ' ' << *it;
    return 0; 
}

Output:

5 4 3 2 1

Example 3: Traverse character set

In this example, we will use begin and end to traverse the set from the first element to the last element and print all elements in order. The set has character values.

#include <iostream> 
#include <set> 
using namespace std; 
   
int main() 
{ 
    
    set<char> myset{'a', 'b', 'c', 'd'}; 
    for (auto it=myset.begin(); it != myset.end(); it++) 
        cout << ' ' << *it; 
    return 0; 
} 
Output :
a b c d

Example 4: Traverse set with user defined objects

#include<bits/stdc++.h> 
using namespace std; 
class Test 
{ 
    public :
            int id; 

            bool operator<(const Test& t) const
            { 
                return (this->id < t.id); 
            } 
}; 
// Driver method 
int main() 
{ 
    // put values in each  
    // structure define below. 
    Test t1 = { 10 }, t2 = { 20 },  
         t3 = { 90 }, t4 = { 100 }; 
  
    set<class Test> s;  
      
    // insert structure in set 
    s.insert(t1);  
    s.insert(t2); 
    s.insert(t3); 
    s.insert(t4); 
      
    // define an iterator to iterate the whole set. 
    set<class Test>::iterator it;  
      
    for (it = s.begin(); it != s.end(); it++) 
    { 
        cout << (*it).id << endl;  
    }
    return 0; 
} 
Output :
10
20
90
100

Application

begin and end function of set has many applications such as:

  1. Very useful while printing all distinct structure in sorted order.
  2. Directly traverse elements in reverse order
  3. Get the last and first element of a set directly
  4. Insert new structure in a sorted list of structures.

Errors and Exceptions

  1. No exception is throw.
  2. Shows error when a parameter is passed.