unordered_set begin() function in C++ STL

The unordered_set::begin() method is a builtin function in C++ STL which is used to return an iterator pointing to the first element in the unordered_set container. All of the iterators of an unordered_set can be used to only access the elements, iterators are not allowed to modify elements present in an unordered_set container.

Note: This iterator can point to either the very first element or the first element of any specified bucket in the unordered_set container.

Syntax:



unordered_set_name.begin(n)

Parameter: This is an optional parameter and specifies the bucket number. If this parameter is not passed then the begin() method will return an iterator pointing to the first element of the container and if this parameter is passed then the begin() method will return an iterator pointing to the first element of the specific bucket in the unordered_set container.

Return Value: This function returns an iterator pointing to the first element in the container or a specified bucket in the container.

Below program illustrate the unordered_set::begin() function:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// unordered_set::begin() function
  
#include <iostream>
#include <unordered_set>
  
using namespace std;
  
int main()
{
  
    unordered_set<int> sampleSet;
  
    // Inserting elements in the std
    sampleSet.insert(5);
    sampleSet.insert(10);
    sampleSet.insert(15);
    sampleSet.insert(20);
    sampleSet.insert(25);
  
    auto itr1 = sampleSet.begin();
    auto itr2 = sampleSet.begin(4);
  
    cout << "First element in the container is: " << *itr1;
    cout << "\nFirst element in the bucket 4 is: " << *itr2;
  
    return 0;
}

chevron_right


Output:

First element in the container is: 25
First element in the bucket 4 is: 15


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.