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:
// C++ program to illustrate the// unordered_set::cbegin() 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.cbegin(); auto itr2 = sampleSet.cbegin(4); cout << "First element in the container is: " << *itr1; cout << "\nFirst element in the bucket 4 is: " << *itr2; return 0;} |
First element in the container is: 25 First element in the bucket 4 is: 15
Program 2:
// C++ program to illustrate the// unordered_set::cbegin() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet; // Inserting elements sampleSet.insert("Welcome"); sampleSet.insert("To"); sampleSet.insert("GeeksforGeeks"); sampleSet.insert("Computer Science Portal"); sampleSet.insert("For Geeks"); auto itr1 = sampleSet.cbegin(); auto itr2 = sampleSet.cbegin(0); cout << "First element in the container is: " << *itr1; cout << "\nFirst element in the bucket 0 is: " << *itr2; return 0;} |
First element in the container is: Welcome First element in the bucket 0 is: GeeksforGeeks



