Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Foreach with key and value pairs

Part of ForeachCategory

Description

You can iterate across associative arrays with both key and value, and also capture the index for static/dynamic arrays.

Example

import std.stdio;

void main() {
    int[char[]] map;
    float[] array;

    map["abc"] = 123;
    map["def"] = 456;
    map["xyz"] = 890;

    array ~= 1.23;
    array ~= 3.14;

    writefln("Iterating over map...");
    foreach (key, value; map)
        writefln("\t%s => %d", key, value);

    writefln("Iterating over array...");
    foreach (index, value; array)
        writefln("\t%d => %f", index, value);
}

Source

This example was originally posted by csauls.