-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathunordered_set_example.c
More file actions
80 lines (69 loc) · 2.38 KB
/
unordered_set_example.c
File metadata and controls
80 lines (69 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <libdsc/unordered_set.h>
#include <stdio.h>
#include <string.h>
// Hash function for strings
static size_t string_hash(void const *key) {
char const *str = *(char const **)key;
size_t hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c;
}
return hash;
}
// Compare function for strings
static int string_compare(void const *a, void const *b) {
char const *str1 = *(char const **)a;
char const *str2 = *(char const **)b;
return strcmp(str1, str2);
}
int main() {
// Create a set of strings
dsc_unordered_set *set =
unordered_set_create(sizeof(char *), string_hash, string_compare);
if (!set) {
printf("Failed to create set\n");
return EXIT_FAILURE;
}
// Insert some elements
char const *elements[] = {"apple", "banana", "orange", "grape", "kiwi"};
for (size_t i = 0; i < 5; ++i) {
if (unordered_set_insert(set, &elements[i]) != DSC_ERROR_OK) {
printf("Failed to insert %s\n", elements[i]);
continue;
}
printf("Inserted %s\n", elements[i]);
}
// Find and print elements
printf("\nFinding elements:\n");
for (size_t i = 0; i < 5; ++i) {
char const **found =
(char const **)unordered_set_find(set, &elements[i]);
if (found) {
printf("Found %s\n", *found);
} else {
printf("Not found: %s\n", elements[i]);
}
}
// Try to find a non-existent element
char const *non_existent = "mango";
char const **found = (char const **)unordered_set_find(set, &non_existent);
printf("\nLooking for non-existent element 'mango': %s\n",
found ? "Found (unexpected)" : "Not found (expected)");
// Try to insert a duplicate
if (unordered_set_insert(set, &elements[0]) == DSC_ERROR_OK) {
printf("\nInserted duplicate %s\n", elements[0]);
}
// Erase an element
if (unordered_set_erase(set, &elements[2]) == DSC_ERROR_OK) {
printf("\nErased %s\n", elements[2]);
found = (char const **)unordered_set_find(set, &elements[2]);
printf("Looking for erased element: %s\n",
found ? "Found (unexpected)" : "Not found (expected)");
}
// Print final size
printf("\nFinal set size: %zu\n", unordered_set_size(set));
// Clean up
unordered_set_destroy(set);
return EXIT_SUCCESS;
}