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
Copy file name to clipboardExpand all lines: content/cpp/concepts/unordered-set/terms/key-eq/key-eq.md
+25-24Lines changed: 25 additions & 24 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -25,13 +25,17 @@ The **`key_eq()`** method returns the equality comparison function object used b
25
25
unordered_set_name.key_eq();
26
26
```
27
27
28
-
**Return Value:**
28
+
**Parameters:**
29
+
30
+
This method takes no parameters.
31
+
32
+
**Return value:**
29
33
30
34
Returns a `key_equal` function object. By default, this is `std::equal_to<T>`, which compares keys using the `==` operator.
31
35
32
36
## Example
33
37
34
-
The following example illustrates retrieving and using the equality comparison function from an unordered_set:
38
+
The following example illustrates retrieving and using the equality comparison function from an `unordered_set`:
35
39
36
40
```cpp
37
41
#include<iostream>
@@ -41,24 +45,28 @@ using namespace std;
41
45
42
46
intmain() {
43
47
unordered_set<int> numbers = {1, 2, 3};
44
-
48
+
45
49
auto eq = numbers.key_eq();
46
-
50
+
47
51
cout << eq(2, 2) << "\n";
48
52
cout << eq(2, 3) << "\n";
49
-
53
+
50
54
return 0;
51
55
}
52
56
```
53
57
54
58
The above program gives the following output:
55
59
56
-
```
60
+
```shell
57
61
1
58
62
0
59
63
```
60
64
61
-
> **Note:** If two keys are considered equal by key_eq(), they must also produce the same hash value. Failing to maintain this consistency results in undefined behavior.
65
+
> **Note:** If two keys are considered equal by `key_eq()`, they must also produce the same hash value. Failing to maintain this consistency results in undefined behavior.
66
+
67
+
## Codebyte Example
68
+
69
+
In this example, a custom case-insensitive equality function is used with `unordered_set`, and `key_eq()` retrieves that function to compare two strings while ensuring duplicate keys are not inserted:
62
70
63
71
```codebyte/cpp
64
72
#include<iostream>
@@ -71,47 +79,40 @@ using namespace std;
71
79
struct CaseInsensitiveHash {
72
80
size_t operator()(const string& str) const {
73
81
size_t hash = 0;
74
-
82
+
75
83
for(char ch : str) {
76
84
hash = hash * 31 + tolower(ch);
77
85
}
78
-
86
+
79
87
return hash;
80
88
}
81
89
};
82
90
83
91
struct CaseInsensitiveEq {
84
92
bool operator()(const string& a, const string& b) const {
0 commit comments