Skip to content
ryru edited this page Feb 28, 2011 · 8 revisions

Map tutorial

Description

Map is a container data type for key/value table.

Basics

#include "map.h"
// ...
map_t persons; // new map instance
map_init(&persons, MAP_STR, sizeof(int)); // constructor
// do some stuff
map_release(&persons); // release memory

Add persons

#include "map.h"
// ...
map_t persons; // new map instance
map_init(&persons, MAP_STR, sizeof(int)); // constructor

// add serval persons with their name as key and age as value
char* p1name = "bob";
int p1age = 33;
map_set(&persons, p1name, &p1age);

char* p2name = "john";
int p2age = 42;
map_set(&persons, p2name, &p2age);

// map now looks like
//
// | key  | value |
// |------|-------|
// | bob  |  33   |
// | john |  42   |

map_release(&persons); // release memory

Find Person

// map looks like
//
// | key  | value |
// |------|-------|
// | bob  |  33   |
// | john |  42   |
// | joe  |  21   |
// | jack |  54   |

int* age = map_find_key(&persons, "joe");
printf("joe is %i years old\n", *age);

int person_age = 42;
char* name = map_find_value(&persons, &person_age);
printf("%s is 42 years old\n", name);

Clone this wiki locally