O(1) dictionaries
Tim Keating
holyspamster at gmail.com
Wed Nov 14 01:04:56 PST 2007
mandel wrote:
> Hi,
>
> I have made a dictionary that way:
> enum Word { Hello, Bye };
> char[][Word] dict;
>
> static this()
> {
> dict = [
> Word.Hello : "Hello",
> Word.Bye : "Bye"
> ];
> }
>
> Now there are two problems I have with this:
>
> - the dict is an AA, but an array would be much faster,
> but it is not possible to assign it via an array literal
> with a mixed order and supplied keys.
> char[][Word.max] dict = [Word.Hello : "Hello", ...]
Why does the array literal have to be in mixed order? You can just do
the enum and the array in the same order:
enum Word { Hello, Bye };
char[] dict = [ "Hello", "Bye" ];
The only complication there is that for a dictionary of any meaningful
length, it won't line up quite as nicely. Ensuring each enum value
matches its correct word will be a real pain. In this situation, I might
use code generation.
> - in place initialisation with a literal is not possible.
> Instead, the use of "static this" makes the code look long winded.
It seems from what you say above that you already know its, but that's
not true anymore. Array literals were recently added to the language
(see the "expressions" section of the language spec).
However, if you think _that's_ long-winded, consider how you would do
that initialization in C++ . . .
TK
More information about the Digitalmars-d
mailing list