开始设计
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
#include <c_HashSet.h>
|
||||
|
||||
// 虛擬佔位常數,所有集合元素在底層對應同一個 Dummy 值的地址
|
||||
static const int dummy_value = 1;
|
||||
|
||||
c_err_t c_HashSet_Init(c_HashSet_t* self, int obj_size, c_size_t initial_capacity,
|
||||
c_HashMap_Hash_f hash, c_HashMap_Compare_f compare) {
|
||||
if (!self) return C_ERR_PARAM;
|
||||
|
||||
// 初始化底層對映的雜湊表,value_size 固定設為常數大小
|
||||
return c_HashMap_Init(&self->map, obj_size, sizeof(int), initial_capacity, hash, compare);
|
||||
}
|
||||
|
||||
void c_HashSet_Destroy(c_HashSet_t* self) {
|
||||
if (!self) return;
|
||||
c_HashMap_Destroy(&self->map);
|
||||
}
|
||||
|
||||
// 推入元素:若元素已存在則攔截並報錯,確保唯一性
|
||||
c_err_t c_HashSet_Add(c_HashSet_t* self, const void* obj) {
|
||||
if (!self || !obj) return C_ERR_PARAM;
|
||||
|
||||
// 先檢查是否已經存在此元素
|
||||
if (c_HashMap_Contains(&self->map, obj)) {
|
||||
return C_ERR_ALREADY_EXISTS;
|
||||
}
|
||||
|
||||
// 將物件當作 Key 寫入,Value 塞入 Dummy 常數
|
||||
return c_HashMap_Put(&self->map, obj, &dummy_value);
|
||||
}
|
||||
|
||||
c_err_t c_HashSet_Remove(c_HashSet_t* self, const void* obj) {
|
||||
if (!self || !obj) return C_ERR_PARAM;
|
||||
return c_HashMap_Remove(&self->map, obj);
|
||||
}
|
||||
|
||||
c_bool_t c_HashSet_Contains(c_HashSet_t* self, const void* obj) {
|
||||
if (!self || !obj) return C_FALSE;
|
||||
return c_HashMap_Contains(&self->map, obj);
|
||||
}
|
||||
|
||||
c_size_t c_HashSet_GetSize(const c_HashSet_t* self) {
|
||||
if (!self) return 0;
|
||||
return self->map.size;
|
||||
}
|
||||
Reference in New Issue
Block a user