cn_map / cn_map_insert

Syntax

CNM_UINT cn_map_insert(CN_MAP map, void * key, void * value)

Description

Inserts a node into map with the key being key and the value being value. If the element already exists, behaviour is undefined.

Return Value

N/A

Examples

Basic Usage (Int as key)

#include <stdio.h>
#include <stdlib.h>

#include "cn_cmp.h"
#include "cn_map.h"

main() {
	//Create a new cn_map
	CN_MAP map = cn_map_init(int, int, cn_cmp_int);

	//Set up key and value
	int key   = 2;
	int value = 4;

	//Insert into the CN_Map
	cn_map_insert(map, &key, &value);

	//Free the CN_Map
	cn_map_free(map);
}

Basic Usage (String as key)

#include <stdio.h>
#include <stdlib.h>

#include "cn_cmp.h"
#include "cn_map.h"

//Frees the key c-string in a CN_Map node when it is removed from the CN_Map
void destruct_key(CNM_NODE *node) {
	char *v = *(char **) node->key;

	if (v != NULL)
		free(v);
}

main() {
	//Create a new cn_map
	CN_MAP map = cn_map_init(char *, int, cn_cmp_cstr);

	//Set the destructor function
	cn_map_set_func_destructor(destruct_key);

	//Setup key and value
	char *key   = "hello";
	int   value = 2;

	//Insert into the CN_Map. Insert duplicate malloc'd string as key.
	char *dup = strdup(key);
	cn_map_insert(map, &dup, &value);

	//Free the CN_Map
	cn_map_free(map);
}