簡易Map


#include
#include

#define INITIAL_MAP_SIZE 10
#define MAP_SIZE_INCREMENT 10
/**************************************
* 構造体
**************************************/
typedef struct _Map {
int size;
char *keys[INITIAL_MAP_SIZE];
char *values[INITIAL_MAP_SIZE];
} Map;

/**************************************
* コンストラクタ
**************************************/
Map *new_Map() {
Map *m;

m = malloc(sizeof(Map));
m->size = 0;
return m;
}

/**************************************
* 追加
**************************************/
int Map_put(Map *m, char *key, char *value) {
int i;

for(i = 0; i < m->size; i++) {
if(strcmp(key, m->keys[i]) == 0) {
strcpy(m->values[i], value);
return i;
}
}

m->keys[m->size] = malloc(strlen(key) + 1);
m->values[m->size] = malloc(strlen(value) + 1);
strcpy(m->keys[m->size], key);
strcpy(m->values[m->size], value);
i = m->size;
m->size++;
return i;
}

/**************************************
* 取得
**************************************/
int Map_get(Map *m, char *key, char *dest) {
int i;

for(i = 0; i < m->size; i++) {
if(strcmp(key, m->keys[i]) == 0) {
strcpy(dest, m->values[i]);
return i;
}
}

return -1;
}

char *Map_getp(Map *m, char *key) {
int i;

for(i = 0; i < m->size; i++) {
if(strcmp(key, m->keys[i]) == 0)
return m->values[i];
}

return NULL;
}

/**************************************
* 削除
**************************************/
int Map_remove(Map *m, char *key, char *dest) {
int i;
char **ppkeys;
char **ppvalues;

ppkeys = m->keys;
ppvalues = m->values;

for(i = 0; i < m->size; i++, ppkeys++, ppvalues++) {
if(strcmp(key, m->keys[i]) == 0) {
if(dest != NULL) strcpy(dest, m->values[i]);
free(m->keys[i]);
free(m->values[i]);
memmove(ppkeys, (ppkeys+1), sizeof(char*) * (m->size - i - 1));
memmove(ppvalues, (ppvalues+1), sizeof(char*) * (m->size - i - 1));
m->size--;
return i;
}
}

return -1;
}

/**************************************
* デストラクタ
**************************************/
void Map_release(Map *m) {
int i;

for(i = 0; i < m->size; i++) {
free(m->keys[i]);
free(m->values[i]);
}

free(m);
}

///////////////////////////////////////

int main() {
Map *m;

m = new_Map();
Map_put(m, "1", "A");
Map_put(m, "2", "B");
Map_put(m, "3", "C");

printf("%s\n", Map_getp(m, "1"));
printf("%s\n", Map_getp(m, "2"));
printf("%s\n", Map_getp(m, "3"));
printf("%s\n", Map_getp(m, "4"));
printf("size: %d\n", m->size);

Map_remove(m, "2", NULL);

printf("%s\n", Map_getp(m, "1"));
printf("%s\n", Map_getp(m, "2"));
printf("%s\n", Map_getp(m, "3"));
printf("%s\n", Map_getp(m, "4"));
printf("size: %d\n", m->size);

Map_put(m, "4", "D");

printf("%s\n", Map_getp(m, "1"));
printf("%s\n", Map_getp(m, "2"));
printf("%s\n", Map_getp(m, "3"));
printf("%s\n", Map_getp(m, "4"));
printf("size: %d\n", m->size);

Map_put(m, "1", "E");

printf("%s\n", Map_getp(m, "1"));
printf("%s\n", Map_getp(m, "2"));
printf("%s\n", Map_getp(m, "3"));
printf("%s\n", Map_getp(m, "4"));
printf("size: %d\n", m->size);

Map_release(m);

return 0;
}