C++ unordered_set begin() Function
Example
Loop through an unordered set with an iterator, and add up all the numbers:
unordered_set<int> numbers = {10, 20, 30, 40};
int sum = 0;
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
sum += *it;
}
cout << "Sum: " << sum;
Definition and Usage
The begin() function returns an iterator (a pointer-like object that points to an element) to the first element of an unordered set.
The elements are not sorted, so the first element can be any of them. This is why begin() is mostly used together with end(), to loop through all the elements. Use *it to get the value.
The begin function is defined in the <unordered_set> header file.
Tip: The auto keyword lets the compiler find the type of the iterator for you. Learn more in the Iterators chapter.
Syntax
unordered_set.begin()
Parameter Values
None.
Technical Details
| Returns: | An iterator pointing to the first element of the unordered set. If the unordered set is empty, it is equal to unordered_set.end(). |
|---|
Related Pages
Read more about unordered sets in our Unordered Set Tutorial.