Open In App

unordered_set begin() function in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

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: 

CPP




// 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;
}


Output:

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

Time Complexity: O(1)
Auxiliary Space: O(1)


Last Updated : 05 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads