Skip to content

Commit e91dada

Browse files
authored
Add C++ unordered_set begin() documentation entry
1 parent 77c540c commit e91dada

File tree

1 file changed

+72
-0
lines changed
  • content/cpp/concepts/unordered-set/terms/begin

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
Title: '.begin()'
3+
Description: 'Returns an iterator pointing to the first element in the unordered_set.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Code Foundations'
7+
Tags:
8+
- 'Methods'
9+
- 'Unordered Sets'
10+
- 'Iterators'
11+
CatalogContent:
12+
- 'learn-c-plus-plus'
13+
- 'paths/computer-science'
14+
---
15+
16+
The **`.begin()`** method returns an iterator pointing to the first element in the `unordered_set` container. Since `unordered_set` is an unordered container, the "first" element is not determined by any particular order.
17+
18+
## Syntax
19+
20+
```cpp
21+
unordered_set.begin();
22+
```
23+
24+
The method takes no parameters and returns an iterator to the first element. If the container is empty, the returned iterator will be equal to `.end()`.
25+
26+
## Example
27+
28+
The following example demonstrates using `.begin()` to iterate through an `unordered_set`:
29+
30+
```cpp
31+
#include <iostream>
32+
#include <unordered_set>
33+
34+
int main() {
35+
std::unordered_set<int> numbers = {10, 20, 30, 40, 50};
36+
37+
std::cout << "Elements in the unordered_set: ";
38+
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
39+
std::cout << *it << " ";
40+
}
41+
42+
return 0;
43+
}
44+
```
45+
46+
This outputs the elements in the unordered_set (order may vary):
47+
48+
```
49+
Elements in the unordered_set: 50 40 30 20 10
50+
```
51+
52+
## Codebyte Example
53+
54+
The following runnable example shows how to use `.begin()` with an `unordered_set`:
55+
56+
```codebyte/cpp
57+
#include <iostream>
58+
#include <unordered_set>
59+
60+
int main() {
61+
std::unordered_set<std::string> fruits = {"apple", "banana", "orange"};
62+
63+
std::cout << "First fruit: " << *fruits.begin() << std::endl;
64+
65+
std::cout << "All fruits: ";
66+
for (auto it = fruits.begin(); it != fruits.end(); ++it) {
67+
std::cout << *it << " ";
68+
}
69+
70+
return 0;
71+
}
72+
```

0 commit comments

Comments
 (0)