Open In App

Implementation on Map or Dictionary Data Structure in C

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 // Maximum number of elements in the map
  
int size = 0; // Current number of elements in the map
char keys[MAX_SIZE][100]; // Array to store the keys
int values[MAX_SIZE]; // Array to store the values
  
// Function to get the index of a key in the keys array
int getIndex(char key[])
{
    for (int i = 0; i < size; i++) {
        if (strcmp(keys[i], key) == 0) {
            return i;
        }
    }
    return -1; // Key not found
}
  
// Function to insert a key-value pair into the map
void insert(char key[], int value)
{
    int index = getIndex(key);
    if (index == -1) { // Key not found
        strcpy(keys[size], key);
        values[size] = value;
        size++;
    }
    else { // Key found
        values[index] = value;
    }
}
  
// Function to get the value of a key in the map
int get(char key[])
{
    int index = getIndex(key);
    if (index == -1) { // Key not found
        return -1;
    }
    else { // Key found
        return values[index];
    }
}
  
// Function to print the map
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.



Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Count-Min Sketch Data Structure with Implementation
The Count-Min Sketch is a probabilistic data structure and is defined as a simple technique to summarize large amounts of frequency data. Count-min sketch algorithm talks about keeping track of the count of things. i.e, How many times an element is present in the set. What is Count-Min Sketch?Count-min sketch approach was proposed by Graham Cormode
7 min read
Heap data structure implementation in swift
A heap is a complete binary tree where each node satisfies the heap property. The heap property is different for different types of heaps but, in general, it means that each node has a value that is greater than or equal to (or less than or equal to) the values of its children nodes. Heaps are commonly used to implement priority queues, as they all
3 min read
Which data structure is used by Map?
What is a Map? Before learning the data structure used by a map, let us have an overlook of map. Map is the part of the STL library that stores key value pairs in it and no two values have the same keys but the different keys can store similar values. The map stores keys in sorted order. These are some functions which map uses with their Time Compl
2 min read
Remove duplicates from unsorted array using Map data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output : 1 2 5 7 4 Explanation : {1, 2} appear more than one time. Approach : Take a hash map, which will store all the
4 min read
Map Policy Based Data Structure in g++
There are some data structures that are supported by g++ compiler and are not a part of the C++ standard library. One of these is: Policy-Based Data Structure, which is used for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std. This can also be used as a map, to store key and a value (pair) in a
3 min read
Sort a 2D vector diagonally using Map Data Structure
Given a 2D vector mat[][] of integers. The task is to sort the elements of the vectors diagonally from top-left to bottom-right in increasing order.Examples: Input: mat[][] = {{9, 4, 2}, {7, 4, 6}, {2, 3, 3}} Output: 3 4 2 3 4 6 2 7 9 Explanation: There are 5 diagonals in this matrix: 1. {2} - No need to sort 2. {7, 3} - Sort - {3, 7} 3. {9, 4, 3}
8 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion and deletion operations are costly in the case of
5 min read
Data Structure for Dictionary and Spell Checker?
Which data structure can be used for efficiently building a word dictionary and Spell Checker? The answer depends upon the functionalists required in Spell Checker and availability of memory. For example following are few possibilities. Hashing is one simple option for this. We can put all words in a hash table. Refer this paper which compares hash
5 min read
Article Tags :
Practice Tags :