c语言中GHashTable的使用(2)
**前言:在上一个文章的基础上增加一些实用的功能,目的在与解决如何利用(a,b)组成的key存储数据
构建hash表g_hash_table_new
//free的函数需要根据自己的实际情况去写,以我自己的结构体为例,在数组里面动态开辟的空间需要循环释放
//使用73856093和19349663解决哈希冲突,也可以自己更改其他的方式
typedef struct
{double *species_density;double cell_electric_V[4];double size;int relative_position;int cell_count;int neighbor_relation[8]; double *species_density_max; double pseudo_collision_max;
} InterfacePoint;
typedef struct
{InterfacePoint *arr;guint count;
} Value;
void free_value_emc(gpointer data)
{Value *val = data;for (guint i = 0; i < val->count; ++i){g_free(val->arr[i].species_density);g_free(val->arr[i].species_density_max);}g_free(val->arr);g_free(val);
}
guint key_hash(gconstpointer key)
{const keyEmc *k = key;return (guint)(k->cell_count * 73856093) ^ (k->time_step * 19349663);
}
gboolean key_equal(gconstpointer a, gconstpointer b)
{const keyEmc *k1 = a;const keyEmc *k2 = b;return k1->cell_count == k2->cell_count && k1->time_step == k2->time_step;
}
void free_key(gpointer data)
{g_free(data);
}
g_hash_table_new_full(key_hash, key_equal, free_key, free_value);
存储方法
这里为了存储类型(1,1.1)形式的key,选择在插入时为y*10000,查询需要同步修改,不影响查询结果
//table hash表,(x,y):key,data_array:存储的数组,一次存储的数组数量
void insert_data_emc(GHashTable *table, int x, double y, InterfacePoint *data_array, guint data_count);void insert_data_emc(GHashTable *table, int x, double y, InterfacePoint *data_array, guint data_count)
{if (data_count > MAX_ARR_SIZE){g_printerr("Error: data_count超过最大容量 %d\n", MAX_ARR_SIZE);return;}
// 创建keyint key_y = (int)(y * 10000);key *key = g_new(keyEmc, 1);key->cell_count = x;key->time_step = key_y;// 看有没有已存在的valueEmcValue *existing = g_hash_table_lookup(table, key);if (existing){// 已有记录,追加但不超过MAX_ARR_SIZEguint can_add = MAX_ARR_SIZE - existing->count;guint to_copy = (data_count < can_add) ? data_count : can_add;for (guint i = 0; i < to_copy; i++){existing->arr[existing->count++] = data_array[i];}g_free(key); // key没插入hash表,自己要释放}else{// 新建valueValue *val = g_new(EmcValue, 1);val->arr = g_new(InterfacePoint, MAX_ARR_SIZE);val->count = 0;for (guint i = 0; i < data_count; i++){val->arr[val->count++] = data_array[i];}g_hash_table_insert(table, key, val);}}
查询方式
如果插入时给y10000,这里就也需要1000
int key_y = (int)(y * 10000);key lookup = {x, key_y};Value *val = g_hash_table_lookup(table, &lookup);