Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <assert.h>
- #include <stdlib.h>
- #include <string.h>
- struct Map {
- int length;
- int allocated;
- char **keys;
- char **values;
- };
- struct Map *Map_create()
- {
- struct Map *map = malloc(sizeof(struct Map));
- assert(map != NULL);
- map->allocated = 0;
- map->length = 0;
- map->keys = NULL;
- map->values = NULL;
- return map;
- }
- char* Map_get(struct Map *map, char *key)
- {
- assert(map != NULL);
- int i;
- for(i = 0; i < map->length; i++){
- if(strcmp(key, map->keys[i]) == 0){
- return map->values[i];
- }
- }
- return NULL;
- }
- int Map_get_key_index(struct Map *map, char *key)
- {
- assert(map != NULL);
- int i;
- for(i = 0; i < map->length; i++){
- if(strcmp(key, map->keys[i]) == 0){
- return i;
- }
- }
- return -1;
- }
- int Map_contains_key(struct Map *map, char *key)
- {
- assert(map != NULL);
- int i;
- for(i = 0; i < map->length; i++){
- if(strcmp(key, map->keys[i]) == 0){
- return 1;
- }
- }
- return 0;
- }
- int Map_contains_value(struct Map *map, char *value)
- {
- assert(map != NULL);
- int i;
- for(i = 0; i < map->length; i++){
- if(strcmp(value, map->values[i]) == 0){
- return 1;
- }
- }
- return 0;
- }
- void Map_remove(struct Map *map, char *key)
- {
- assert(map != NULL);
- // check if key exists and get its index
- int k = Map_get_key_index(map, key);
- int i = 0;
- if(k > -1){
- // map is now shorter
- map->length--;
- // shift all the key/values pairs
- // after the "erased pair" upwards
- for(i = k; i < map->length; i++){
- map->keys[i] = map->keys[i+1];
- map->values[i] = map->values[i+1];
- }
- }
- }
- void Map_put(struct Map *map, char *key, char *value)
- {
- assert(map != NULL);
- int i = Map_get_key_index(map, key);
- int k; // index of the new key/value pair
- if(i > -1){
- // will overwrite existing value if key already exists
- k = i;
- }else{
- // will add a new key/value pair
- // check if there's enough space
- if(map->length == map->allocated){
- // allocate more space
- if(map->allocated == 0){
- // begin allocating 2
- map->allocated = 2;
- }else{
- // double if more is needed
- map->allocated *= 2;
- }
- void *tmp_keys = realloc(map->keys, map->allocated * sizeof(key));
- void *tmp_values = realloc(map->values, map->allocated * sizeof(value));
- map->keys = (char**)tmp_keys;
- map->values = (char**)tmp_values;
- }
- // increase the length
- k = map->length;
- map->length = k + 1;
- }
- // write key/value pair to k index
- map->keys[k] = key;
- map->values[k] = value;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement