19

I want to implement a key value pair data structure in C. Any idea?

royhowie
  • 11,075
  • 14
  • 50
  • 67
Udara S.S Liyanage
  • 6,189
  • 9
  • 33
  • 34

3 Answers3

12

This is a simple hash table implementation in ANSI C. It supports the rudimentary functions generally expected of a hash table:

  • Inserting and retrieving key-value associations
  • Querying the existence of a key
  • Returning the total number of key-value associations
  • Enumerating over all key-value associations

Hope this helps!

  • 10
    Actually, to be a bit pedantic, that is not ANSI C since it defines functions whose names start with "str". You can't do that, the entire space of global functions names that start with "str" is reserved. – unwind Apr 14 '11 at 09:06
  • I don't like it, because it doesn't specify th esource code of the functions, and it does not seem to expand or shrink. It just has a fixed number of items. –  Jul 11 '20 at 01:30
10

If your key and value part are same data type then you can use a 2-D array with 2 column where first column will be your key and second will be data. IT will behave as map but time complexity will diff. Time complexity : search - O(n) Insert - want to maintain unique key then O(n) else O(1).

int map[N][2];

if you want to have key-value pair different type then you can use list structure.

struct node
{
int key;  //key part
string value;  // value part
struct node *next;
};

Time complexity : search - O(n) Insert - want to maintain unique key then O(n) else O(1).

sitaram chhimpa
  • 471
  • 7
  • 12
1

Typical map functions are also supported by the hashmap implementation in libmba.

I found about it a while ago, though I haven't used it. You can also check the library project homepage.

I hope it might be prove useful to someone.

Nikopol
  • 1,091
  • 1
  • 13
  • 24