Skip to content

Commit 5bf6621

Browse files
committed
Add C++ unordered-set empty() term entry
1 parent 95f0e9a commit 5bf6621

File tree

1 file changed

+97
-0
lines changed
  • content/cpp/concepts/unordered-set/terms/empty

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
---
2+
Title: '.empty()'
3+
Description: 'Checks whether the unordered set is empty.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Game Development'
7+
Tags:
8+
- 'Containers'
9+
- 'Functions'
10+
- 'Sets'
11+
- 'STL'
12+
CatalogContent:
13+
- 'learn-c-plus-plus'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`.empty()`** method checks whether an [`unordered_set`](https://www.codecademy.com/resources/docs/cpp/unordered-set) container has no elements. It returns `true` if the container is empty (i.e., its size is 0) and `false` otherwise.
18+
19+
## Syntax
20+
21+
```pseudo
22+
unordered_set_name.empty()
23+
```
24+
25+
- `unordered_set_name`: The name of the `unordered_set` being checked for emptiness.
26+
27+
**Parameters:**
28+
29+
This method does not take any parameters.
30+
31+
**Return Value:**
32+
33+
Returns `true` if the `unordered_set` is empty and `false` otherwise.
34+
35+
## Example
36+
37+
The following example demonstrates how to use the `.empty()` method with `std::unordered_set` in C++:
38+
39+
```cpp
40+
#include <iostream>
41+
#include <unordered_set>
42+
43+
int main() {
44+
std::unordered_set<int> numbers;
45+
46+
if (numbers.empty()) {
47+
std::cout << "Unordered set is empty\n";
48+
} else {
49+
std::cout << "Unordered set has elements\n";
50+
}
51+
52+
numbers.insert(10);
53+
numbers.insert(20);
54+
numbers.insert(30);
55+
56+
if (numbers.empty()) {
57+
std::cout << "Unordered set is empty\n";
58+
} else {
59+
std::cout << "Unordered set has elements\n";
60+
}
61+
62+
return 0;
63+
}
64+
```
65+
66+
The output of the above code is:
67+
68+
```shell
69+
Unordered set is empty
70+
Unordered set has elements
71+
```
72+
73+
## Codebyte Example
74+
75+
In this example, the `.empty()` method is used to control a loop that processes and removes elements from an `unordered_set` until it becomes empty:
76+
77+
```codebyte/cpp
78+
#include <iostream>
79+
#include <unordered_set>
80+
81+
int main() {
82+
std::unordered_set<int> numbers = {5, 10, 15, 20, 25};
83+
84+
std::cout << "Processing elements: ";
85+
86+
while (!numbers.empty()) {
87+
auto it = numbers.begin();
88+
std::cout << *it << " ";
89+
numbers.erase(it);
90+
}
91+
92+
std::cout << "\n";
93+
std::cout << "Unordered set is now empty: " << std::boolalpha << numbers.empty() << "\n";
94+
95+
return 0;
96+
}
97+
```

0 commit comments

Comments
 (0)