Ghashtable allows you to store data in the form of a metadata table. When storing data, you can specify the key to calculate the hash value to determine the storage location of the data. You need to retrieve the data, it also specifies the key to calculate the storage location of the data to quickly obtain the data.
Simply put, you can use ghashtable as a house with many rooms. Each room has a pair of keys, when you save the data to the room, You need to upload a key. The next time you want to retrieve the data, you need to get the key "root.
You can use g_hash_table_new () to create a ghashtable:
Ghashtable * g_hash_table_new (ghashfunc hash_func,
Gequalfunc key_equal_func );
G_hash_table_new () specifies a function for calculating the hash value. Glib provides functions such as g_int_hash () and g_str_hash () that can be directly used, you can also calculate the hash value from the handler, for example:
Guint hash_func (gconstpointer key ){
...
Return ...;
}
The hash algorithm determines the storage location of the shard. Next, we need to confirm the key equality. Glib provides the g_int_equal () and g_str_equal () functions that can be directly used, in the same way, you can also customize the function:
Gboolean key_cmd_func (gconstpointer A, gconstpointer B ){
...
Return ...;
}
The following program is a simple example:
#include <glib.h>
int main(int argc, char *argv[]) {
GHashTable *hashTable = g_hash_table_new(
g_str_hash, g_str_equal);
g_hash_table_insert(hashTable, "caterpillar", "caterpillar's message!!");
g_hash_table_insert(hashTable, "justin", "justin's message!!");
g_print("%s/n", g_hash_table_lookup(hashTable, "caterpillar"));
g_print("%s/n", g_hash_table_lookup(hashTable, "justin"));
g_hash_table_destroy(hashTable);
return 0;
}
The program's response results are as follows:
Justin's message !! Caterpillar's message !!
|
The following shows how to use the g_hash_table_iter_next () function of the worker to perform the ghashtable iteration:
#include <glib.h>
int main(int argc, char *argv[]) {
GHashTableIter iter;
gpointer key, value;
GHashTable *hashTable;
hashTable = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_insert(hashTable, "justin", "justin's message!!");
g_hash_table_insert(hashTable, "momor", "momor's message!!");
g_hash_table_insert(hashTable, "caterpillar", "caterpillar's message!!");
g_hash_table_iter_init (&iter, hashTable);
while(g_hash_table_iter_next(&iter, &key, &value)) {
g_print("key/t: %s/nvalue/t: %s/n/n", key , value);
}
g_hash_table_destroy(hashTable);
return 0;
}
The program's response results are as follows:
Key: Justin Value: Justin's message !!Key: Caterpillar Value: Caterpillar's message !! Key: momor Value: momor's message !!
|