Re: Is remove safe using foreach

2022-12-17 Thread j via Digitalmars-d-learn
On Monday, 12 December 2022 at 17:23:36 UTC, lili wrote: ``` int[string] aa = ["ok":1, "aaa":2, "ccc":3, "ddd":4]; foreach (k ; aa.byKey) { if (k == "aaa") { aa.remove(k); aa["ww"] = 33; } if (k ==

Re: Is remove safe using foreach

2022-12-13 Thread Steven Schveighoffer via Digitalmars-d-learn
On 12/13/22 6:22 AM, Per Nordlöw wrote: On Monday, 12 December 2022 at 17:29:00 UTC, Steven Schveighoffer wrote: Removing keys while iterating is not supported. It will break, in confusing ways, and possibly include a null pointer dereference. IRC, the specs says that it's an error to modify

Re: Is remove safe using foreach

2022-12-13 Thread Per Nordlöw via Digitalmars-d-learn
On Monday, 12 December 2022 at 17:29:00 UTC, Steven Schveighoffer wrote: Removing keys while iterating is not supported. It will break, in confusing ways, and possibly include a null pointer dereference. IRC, the specs says that it's an error to modify a foreach aggregate but the compiler

Re: Is remove safe using foreach

2022-12-13 Thread Per Nordlöw via Digitalmars-d-learn
On Tuesday, 13 December 2022 at 11:22:35 UTC, Per Nordlöw wrote: IRC, the specs says that it's an error to modify a foreach aggregate but the compiler curretly doesn't diagnose it. I believe it should.

Re: Is remove safe using foreach

2022-12-12 Thread Steven Schveighoffer via Digitalmars-d-learn
On 12/12/22 8:45 PM, Steven Schveighoffer wrote: for(auto r = aa.byKey, auto k = r.front; !r.empty; r.popFront) err... forgot the continual front assignment I think it's more like: for(auto r = aa.byKey; !r.empty; r.popFront) { auto k = r.front; // foreach body } -Steve

Re: Is remove safe using foreach

2022-12-12 Thread Steven Schveighoffer via Digitalmars-d-learn
On 12/12/22 7:54 PM, lili wrote: is foreach Syntactic sugar?, like for-range in C++, if it is, compiler how implement Yes it is syntax sugar. The lowering depends on what the item you're iterating is. For an associative array `byKey`, it is converting the AA into a range of keys, and

Re: Is remove safe using foreach

2022-12-12 Thread lili via Digitalmars-d-learn
is foreach Syntactic sugar?, like for-range in C++, if it is, compiler how implement

Re: Is remove safe using foreach

2022-12-12 Thread Steven Schveighoffer via Digitalmars-d-learn
On 12/12/22 12:23 PM, lili wrote: ``` int[string] aa = ["ok":1, "aaa":2, "ccc":3, "ddd":4]; foreach (k ; aa.byKey) {     if (k == "aaa") {     aa.remove(k);     aa["ww"] = 33;     }     if (k == "ww") {     aa.remove(k);     aa["vv"] = 33;     }

Is remove safe using foreach

2022-12-12 Thread lili via Digitalmars-d-learn
``` int[string] aa = ["ok":1, "aaa":2, "ccc":3, "ddd":4]; foreach (k ; aa.byKey) { if (k == "aaa") { aa.remove(k); aa["ww"] = 33; } if (k == "ww") { aa.remove(k);