How to make a struct containing an associative array to deeply copy (for repeated usage in foreach) ?

rkompass rkompass at gmx.de
Wed Mar 13 22:16:52 UTC 2024


I want to make a custom dictionary that I may iterate through 
with foreach. Several times.
What I observe so far is that my dict as a simple forward range 
is exhausted after the first foreach and I have to deeply copy it 
beforehand.
With a simple associative array the exhaustion is not observed.
Is there a (hopefully simple) way to make this 
automatic/transparent? Of course
I need to use the struct.
Can I add a save member function? If yes: How? Or is there an 
operator that is used in the foreach initialization that I may 
overload in this struct?

My code:
```d
import std.stdio;
import std.string;
import std.typecons;

struct mydict {
    string[string] dct;

    @property bool empty() const {
       return dct.empty;
    }
    @property ref auto front() {
       return tuple(dct.keys[0], dct[dct.keys[0]]);
    }
	void popFront() {
		dct.remove(dct.keys[0]);
	}
	void opAssign(mydict rhs) {
		writeln("--opAssign--");
		foreach (k; rhs.dct.keys)  // do a deep copy
			dct[k] = rhs.dct[k];
	}
}

void main() {

	mydict md, md2;
	md.dct = ["h":"no", "d":"ex", "r": "cow"];
	md2 = md;             // md2.opAssign(md)
	foreach (k, v; md)
		writeln("key: ", k, "val: ", v);
	writeln("----------");
	foreach (k, v; md)   // does not work with md again, md is 
exhausted
		writeln("key: ", k, "val: ", v);
}
```


More information about the Digitalmars-d-learn mailing list