Implementation on Map or Dictionary Data Structure in C
Last Updated :
27 Mar, 2023
C programming language does not provide any direct implementation of Map or Dictionary Data structure. However, it doesn’t mean we cannot implement one. In C, a simple way to implement a map is to use arrays and store the key-value pairs as elements of the array.
How to implement Map in C?
One approach is to use two arrays, one for the keys and one for the values, where the key at index i in the key array corresponds to the value at index i in the value array.
- Variables used to implement Map in C
- This implementation uses two arrays, keys and values, to store the key-value pairs.
- The maximum number of elements in the map is defined as MAX_SIZE.
- The size variable keeps track of the current number of elements in the map.
- Functions used to implement Map in C
- The getIndex function searches for a key in the keys array and returns its index if found, or -1 if not found.
- The insert function inserts a key-value pair into the map. If the key already exists, it updates the value.
- The get function returns the value of a key in the map, or -1 if the key is not found.
- The printMap function prints all the key-value pairs in the map.
- In the main function, we insert some key-value pairs into the map, get the value of some keys, and print the map.
Here’s an example implementation of a map using arrays:
C
#include <stdio.h>
#include <string.h>
#define MAX_SIZE \
100
int size = 0;
char keys[MAX_SIZE][100];
int values[MAX_SIZE];
int getIndex( char key[])
{
for ( int i = 0; i < size; i++) {
if ( strcmp (keys[i], key) == 0) {
return i;
}
}
return -1;
}
void insert( char key[], int value)
{
int index = getIndex(key);
if (index == -1) {
strcpy (keys[size], key);
values[size] = value;
size++;
}
else {
values[index] = value;
}
}
int get( char key[])
{
int index = getIndex(key);
if (index == -1) {
return -1;
}
else {
return values[index];
}
}
void printMap()
{
for ( int i = 0; i < size; i++) {
printf ( "%s: %d\n" , keys[i], values[i]);
}
}
int main()
{
insert( "Geeks" , 5);
insert( "GFG" , 3);
insert( "GeeksforGeeks" , 7);
printf ( "Value of complete Map: \n" );
printMap();
printf ( "\nValue of apple: %d\n" , get( "GFG" ));
printf ( "Index of GeeksforGeeks: %d\n" ,
getIndex( "GeeksforGeeks" ));
return 0;
}
|
Output
Value of complete Map:
Geeks: 5
GFG: 3
GeeksforGeeks: 7
Value of apple: 3
Index of GeeksforGeeks: 2
This implementation is simple and easy to understand, but it has some limitations. One limitation is that the keys must be unique, otherwise the insert function will overwrite the value of an existing key. Another limitation is that the maximum size of the map is fixed, and if we exceed the maximum size, we cannot insert any more elements into the map.
Please Login to comment...