Task

The goal is to create an associative array (also known as a dictionary, map, or hash).



Related tasks:

 Associative arrays/Iteration
 Hash from two arrays


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


#define max(a, b) Iif(a>b,a,b)
 
enum datatype
    'for this demonstration we'll allow these five data types
    BOOL
    STRNG
    BYYTE
    INTEG
    FLOAT
end enum
 
union value
    bool as boolean
    strng as string*32
    byyte as byte
    integ as integer
    float as double
end union
 
type dicitem
    'one part of the dictionary entry, either the key or the value
    datatype as datatype   'need to keep track of what kind of data it is
    value as value
end type
 
type dicentry
    'a dic entry has two things, a key and a value
    key as dicitem
    value as dicitem
end type
 
sub add_dicentry( Dic() as dicentry, entry as dicentry )
    redim preserve Dic(0 to max(ubound(Dic)+1,0))
    Dic(ubound(Dic)) = entry
    return
end sub
 
redim as dicentry Dictionary(-1)  'initialise a dictionary with no entries as yet
 
dim as dicentry thing1, thing2
 
'generate some test dictionary entries
with thing1
    with .key
        .datatype = STRNG
        .value.strng = "Cat"
    end with
    with .value
        .datatype = STRNG
        .value.strng = "Mittens"
    end with
end with
 
with thing2
    with .key
        .datatype = integ
        .value.integ = 32767
    end with
    with .value
        .datatype = float
        .value.float = 2.718281828
    end with
end with
 
add_dicentry( Dictionary(), thing1 )
add_dicentry( Dictionary(), thing2 )
 
print Dictionary(0).value.value.strng
print Dictionary(1).key.value.integ