Struct HashMap

struct HashMap(K, V, Allocator, bool GCRangesAllowed = true) ;

Methods

NameDescription
addIfMissed Add key/value to hash if key is not in table. value can be lazy/callable.
byKey iterator by keys
byPair iterator by key/value pairs
byValue iterator by values
clear throw away all keys
get get
getOrAdd get value from hash or add if key is not in table. defaultValue can be callable.
grow_factor get current grow factor.
grow_factor set grow factor (can be between 2, 4 or 8).
keyPointer
length get numter of keys in table
opBinaryRight key in table
opIndex map[key]
opIndexAssign map[k] = v;
put put pair (k,v) into hash.
remove remomve key from hash.
size get current buckets number

Inner structs

NameDescription
KeyPointer

Aliases

NameDescription
require

Example

Example

import std.range;
import std.algorithm;

HashMap!(string, int) counter;
string[] words = ["hello", "this", "simple", "example", "should", "succeed", "or", "it", "should", "fail"];
// count words, simplest and fastest way
foreach (word; words)
{
    counter.getOrAdd(word, 0)++;
}
assert("world" !in counter);
assert(counter["hello"] == 1);
assert(counter["should"] == 2);
assert(counter.length == words.length - 1);
// clear counter
counter.clear;
assert(counter.length == 0);
// more verbose way to count
foreach (word; words)
{
    auto w = word in counter;
    if (w)
    {
        (*w)++;
    }
    else
    {
        counter[word] = 1;
    }
}
assert("world" !in counter);
assert(counter["hello"] == 1);
assert(counter["should"] == 2);
assert(counter.length == words.length - 1);
// iterators
assert(counter.byKey.count == counter.byValue.count);
assert(words.all!(w => w in counter));          // all words are in table
assert(counter.byValue.sum == words.length);    // sum of counters must equals to number of words