unordered_set cbegin() function in C++ STL

The unordered_set::cbegin() method is a built-in function in C++ STL which is used to return a const_iterator pointing to the first element in the unordered_set container. This iterator can point to either the very the first element or first element of any specified bucket in the unordered_set container.

Note: A const_iterator can only be used to access elements, it cannot modify the elements present in the container.

Syntax:

unordered_set_name.cbegin(n)

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

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

Below programs illustrate the unordered_set::cbegin() function:

Program 1:

filter_none

editclose

play_arrow

linkbrightness_4code

// C++ program to illustrate the

// unordered_set::cbegin() function

#include <iostream>

#include <unordered_set>

usingnamespacestd;

intmain()

{

unordered_set<int> sampleSet;

// Inserting elements in the std

sampleSet.insert(5);

sampleSet.insert(10);

sampleSet.insert(15);

sampleSet.insert(20);

sampleSet.insert(25);

autoitr1 = sampleSet.cbegin();

autoitr2 = sampleSet.cbegin(4);

cout << "First element in the container is: "<< *itr1;

cout << "\nFirst element in the bucket 4 is: "<< *itr2;

return0;

}

chevron_right

filter_none

Output:

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

Program 2:

filter_none

editclose

play_arrow

linkbrightness_4code

// C++ program to illustrate the

// unordered_set::cbegin() function

#include <iostream>

#include <unordered_set>

usingnamespacestd;

intmain()

{

unordered_set<string> sampleSet;

// Inserting elements

sampleSet.insert("Welcome");

sampleSet.insert("To");

sampleSet.insert("GeeksforGeeks");

sampleSet.insert("Computer Science Portal");

sampleSet.insert("For Geeks");

autoitr1 = sampleSet.cbegin();

autoitr2 = sampleSet.cbegin(0);

cout << "First element in the container is: "<< *itr1;

cout << "\nFirst element in the bucket 0 is: "<< *itr2;

return0;

}

chevron_right

filter_none

Output:

First element in the container is: Welcome
First element in the bucket 0 is: GeeksforGeeks

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.