C++ cbegin()
The cbegin() method returns a constant iterator that points to the first element of an unordered_set. A constant iterator allows read-only access to elements and prevents modification. Because unordered_set does not maintain any defined order, the element returned by cbegin() depends on its internal hash table structure.
Syntax
unordered_set_name.cbegin(n);
Return value:
Returns a const_iterator (constant iterator) pointing to the first element in the unordered_set.
Or, alternatively:
unordered_set_name.cbegin(n);
Parameters:
n(size_type): The bucket index. Must be less thanbucket_count().
Return value:
A const_local_iterator pointing to the first element in bucket n. If the bucket is empty, the returned iterator equals cend(n).
Example
This example demonstrates obtaining the starting element of an unordered_set using cbegin():
#include <iostream>#include <string>#include <unordered_set>using namespace std;int main() {unordered_set<int> unique_numbers = {10, 5, 20, 15};auto it = unique_numbers.cbegin();cout << "The first element in internal order is: " << *it << "\n";++it;if (it != unique_numbers.cend()) {cout << "The second element is: " << *it << "\n";}// *it = 99; // Error: cannot modify through const_iteratorreturn 0;}
A sample output of this code is:
The first element in the set's internal order is: 20The second element is: 5
Note: Attempting to modify the element pointed to by the
const_iteratorwould result in a compilation error.
Codebyte Example
In this example, the code retrieves a constant iterator for a specific bucket in the unordered_set and prints all elements stored in that bucket:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours