2023-01-03, 12:17 AM
2023-01-03: Hash Maps
A hash map is similar to an array, but instead of a number to access things it takes a string. YSI has basic hash map support via y_hashmap (note that this is different to y_stringhash, although they do share a basic hash algorithm so both libraries will give the same numeric representation of a string).
The hash map functions convert a string to an array index, which can be subsequently used to access data.
Given the following data you want to add string indexing to:
The enum must have a string added, which becomes the name, and some extra data:
You can use the name in your own code, the hash map data is an implementation detail.
Initialise the data with the enum offsets:
Add an item by name (to enable y_hashmap to translate the given name to the given index):
This will also set the name in the array at the given index, so you don't need to do that yourself.
Look up an index by name:
You can now use id as in index in to gData.
There are more functions to remove items and get entires in clever ways. See the library for more information.
A hash map is similar to an array, but instead of a number to access things it takes a string. YSI has basic hash map support via y_hashmap (note that this is different to y_stringhash, although they do share a basic hash algorithm so both libraries will give the same numeric representation of a string).
The hash map functions convert a string to an array index, which can be subsequently used to access data.
Given the following data you want to add string indexing to:
Quote:
enum E_MY_DATA
{
____E_DATA_INT,
____E_DATA_FLOAT
}
new gData[MAX_ENTRIES][E_MY_DATA];
The enum must have a string added, which becomes the name, and some extra data:
Quote:
enum E_MY_DATA
{
____// Must come first.
____E_DATA_NAME[32],
____// Must come second.
____E_DATA_HASH_DATA[HASH_MAP_DATA],
____// Normal enum contents.
____E_DATA_INT,
____E_DATA_FLOAT
}
new gData[MAX_ENTRIES][E_MY_DATA];
new HashMap:gHashMap<>;
You can use the name in your own code, the hash map data is an implementation detail.
Initialise the data with the enum offsets:
Quote:
HashMap_Init(gHashMap, gData, E_DATA_HASH_DATA);
Add an item by name (to enable y_hashmap to translate the given name to the given index):
Quote:
HashMap_Add(gHashMap, name, id),
This will also set the name in the array at the given index, so you don't need to do that yourself.
Look up an index by name:
Quote:
new id = HashMap_Get(gHashMap, "name");
You can now use id as in index in to gData.
There are more functions to remove items and get entires in clever ways. See the library for more information.