October 22, 2022

On Saturday, 22 October 2022 at 15:21:07 UTC, Kevin Bailey wrote:

>

OTOH, a forward iterator (i.e. copyable but does not need to
go backwards) solves the problem elegantly and efficiently.

The builtin function byKeyValue returns a forward range (D's version of a forward iterator) over the contents of an associative array. To save the current iteration state, use the .save method.

Here's a simple example:

import std.algorithm, std.range, std.stdio;

void main()
{
    auto aa = ["x": 123, "y": 456, "z": 789, "w": 10];

    // name of range type is private, so use auto + typeof
    auto it = aa.byKeyValue;
    typeof(it) saved;

    // iterate once and save our position partway through
    for (; !it.empty; it.popFront)
    {
        auto e = it.front;
        if (e.key == "y")
            saved = it.save;
        writefln("%s: %s", e.key, e.value);
    }

    writeln("--------");

    // iterate again from saved position
    foreach (e; saved)
        writefln("%s: %s", e.key, e.value);
}
October 22, 2022
On 10/22/22 08:21, Kevin Bailey wrote:

> his claim that there was no value.

I think he was questioning the need for iterating from a point forward inside an unordered container. When the container is unordered, the elements that are accessed after a found element could be anything. I think that's the puzzling part in your question.

>      package main

Here is my interpretation of Paul Backus's solution:

module main;

import std.stdio;

void main() {
    int[string] m;
    m["key1"] = 7;
    m["key2"] = 8;

    auto iter = m.byKeyValue();
    // Advance iterator
    iter.popFront();
    // Preserve position
    auto iter2 = iter.save();
    // Exhaust first iterator
    foreach (kv; iter) {
        writeln("iter: ", kv.key, " = ", kv.value);
    }
    // What does second iterator see?
    foreach (kv; iter2) {
        writeln("iter2: ", kv.key, " = ", kv.value);
    }
}

May print (because its unordered):

iter: key2 = 8
iter2: key2 = 8

Ali

October 22, 2022
ah, I knew that I could iterate over byKey, but I didn't know that it was a
tangible thing, that you could hold in your hand. This should be fine, and
I'll use your template trick for passing it to a function.

Thanks Paul and Ali!

October 22, 2022

On 10/22/22 12:53 AM, Kevin Bailey wrote:

>

Steven,

Just because you don't see the value doesn't mean I don't. You should try to
be more helpful, or don't bother.

I just mean that I don't understand what iterating from a random position in the AA is. Why not iterate from the beginning? It isn't any different.

-Steve

1 2
Next ›   Last »