dictionary/map/key-value pairs data structure in C

后端 未结 4 1696
借酒劲吻你
借酒劲吻你 2021-01-07 06:38

How does one construct and access a set of key-value pairs in C? To use a silly simple example, let\'s say I want to create a table which translates between an integer and i

相关标签:
4条回答
  • 2021-01-07 06:57

    You can use map implemented as part of clib library

    0 讨论(0)
  • 2021-01-07 06:59

    You could consider hash implementation in C language to achieve this. For basics of hash refer to Wikipedia. Refer to this question for more details and links.

    This link gives good overview and implementation details.

    0 讨论(0)
  • 2021-01-07 07:00

    There is no built-in way to do this unless you count initializing an array like this in C99:

    double squareRoots[] =
    {
         [4] = 2.0,
         [9] = 3.0,
        [16] = 4.0,
        [25] = 5.0,
    };
    

    However, this allocates 26 elements in the array; the other values are all zeroes.

    Assuming you didn't mean this, then look at C Interfaces and Implementations by D R Hanson; it shows a way of implementing associative arrays (aka hashes or dictionaries).

    0 讨论(0)
  • 2021-01-07 07:11

    You could also use the libghthash for general purpose hashes. They are quite easy to use, and incorporate in your application. However, it is a third party API - so if that's a problem, you would have to implement your own.

    There's no built in associate array/hash tables in C.

    The array initialization (C99) is probably the best way to go unless you have non-numeric keys:

    T hash[] = {
        [1] = tObj,
        [255] = tObj2,
    };
    
    0 讨论(0)
提交回复
热议问题