i'm using two lists of the above example, one for storing the key and the other for the value. the map type is defined as follows:

 Code:
typedef struct {
    LIST *keys, *values;
} MAP;


implementation of the functins new/add/remove/delete is like above.

 Code:
MAP* new_map(void)
{
	MAP* map = (MAP*)malloc(sizeof(MAP));
	if (map == NULL) {
		return (MAP*)NULL;
	}

	// two lists containing keys and values
	map->keys = new_list();
	map->values = new_list();
	if (!map->keys || !map->values) {
		return (MAP*)NULL;
	}
	
	return map;	
}

bool delete_map(MAP *map, bool garbage_keys, bool garbage_values)
{
	if (map == NULL) {
		return false;
	}
	
	// autodelete all items
	if (!delete_list(map->keys, garbage_keys) || !delete_list(map->values, garbage_values)) {
		return false;
	}
	
	free(map);
	return true;
}


var map_size(MAP* map)
{
	if (map == NULL) {
		return -1;
	}
	
	return list_size(map->keys);	
}

bool map_add(MAP* map, void* key, void* value)
{
	if (map == NULL) {
		return false;
	}
	
	if (!list_add(map->keys, key) || !list_add(map->values, value)) {
		return false;
	}
	
	return true;
}

void* map_get(MAP* map, void* key)
{
	if (map == NULL) {
		return NULL;
	}
	
	return list_get(map->values, list_index_of(map->keys, key));
}

bool map_delete(MAP* map, void* key)
{
	if (map == NULL) {
		return false;
	}
	
	var offset = list_index_of(map->keys, key);
	if (offset == -1) {
		return false;
	}
	
	if (!list_delete(map->keys, offset) || !list_delete(map->values, offset)) {
		return false;
	}
	
	return true;
}


note that it doesn't work for hardcoded values since it also works with pointers for the keys. the advantage is that you can simply add a hashmap to an entity, a panel or whatever else you can imagine.

joey.

Last edited by Joey; 04/14/08 21:34. Reason: added hint