You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Description: 'Returns the number of elements with a specific key in an unordered_set.'
4
4
Subjects:
5
+
- 'Code Foundations'
5
6
- 'Computer Science'
6
-
- 'Programming'
7
7
Tags:
8
-
- 'C++'
9
-
- 'Unordered Set'
8
+
- 'Methods'
9
+
- 'Sets'
10
10
- 'STL'
11
-
- 'Searching'
12
11
CatalogContent:
13
12
- 'learn-c-plus-plus'
14
13
- 'paths/computer-science'
15
14
---
16
15
17
-
The **`.count()`** method is used to determine if a specific element (key) is present within a C++ `std::unordered_set`.
16
+
The **`count()`** method checks whether a given key exists in a `std::unordered_set`. Since this container stores only unique elements, `count()` will always return either:
18
17
19
-
Because `std::unordered_set` only allows **unique** elements, the `.count()` method will only ever return one of two possible values:
20
-
21
-
1.**`1`**: If the element is found in the set.
22
-
2.**`0`**: If the element is not found in the set.
18
+
1.`1`: If the element is found in the set.
19
+
2.`0`: If the element is not found in the set.
23
20
24
21
This method is commonly used as a fast, O(1) average time complexity way to check for element existence.
25
22
26
23
## Syntax
27
24
28
-
The `.count()` method takes one argument: the value (key) to search for.
29
-
30
-
```cpp
25
+
```pseudo
31
26
unordered_set_name.count(key);
32
27
```
33
28
34
-
## Parameters
29
+
**Parameters:**
35
30
36
-
*`key` (const Key&): The value of the element to search for. Must be of the same type as the elements stored in the `unordered_set`.
31
+
-`key` (const Key&): The value of the element to search for. Must be of the same type as the elements stored in the `unordered_set`.
37
32
38
-
## Return Value
33
+
**Return value:**
39
34
40
-
Returns an integer (`1` if the element exists, `0` otherwise).
35
+
Returns an integer. `1` if the element exists, `0` otherwise.
41
36
42
37
## Example
43
38
44
-
This example demonstrates using `.count()` to check for the presence of elements within a set of strings.
39
+
This example demonstrates using `count()` to check for the presence of elements within a set of strings:
45
40
46
41
```cpp
47
42
#include<iostream>
@@ -74,9 +69,9 @@ int main() {
74
69
}
75
70
```
76
71
77
-
Output:
72
+
The output of the code is:
78
73
79
-
```
74
+
```shell
80
75
Inventory contains:
81
76
- Potion
82
77
- Shield
@@ -86,28 +81,28 @@ Inventory contains:
86
81
'Axe' is not present (Count: 0).
87
82
```
88
83
89
-
## Codebyte
84
+
## Codebyte Example
90
85
91
-
Use the Codebyte below to check for the presence of an item in a set of integers.
86
+
Use the Codebyte below to check for the presence of an item in a set of integers:
0 commit comments