On 6/21/15 7:02 PM, Andrei Alexandrescu wrote:
While I work on making std.allocator better, here's some food for
thought regarding std.collection.

Consider a traditional container with reference semantics, Java-style.
Regarding changing the collection (e.g. adding/removing elements) while
iterating, we have the following possibilities:

1. Leave it undefined, like the STL does. Probably this is too extreme.

I don't think it's undefined, it depends on the container:

http://www.cplusplus.com/reference/set/set/erase/

"Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity."

I do the same for dcollections.

Note that I support a mechanism whereby the user can choose to remove *while* iterating (I call it purging) via the container itself.

One of the main reasons I wrote dcollections in the first place is because I had a requirement to remove while iterating. The use case was a map of processes I was keeping track of, looking for ones that were done so they could be removed. In effect, I would do a foreach on the container, and add keys of the elements I'd like to remove to an array. Then afterward, I would use the key array to remove all those elements (these were Tango containers). I didn't like that second step, nor the inefficiency of building another array that I was going to discard.

With dcollections, this becomes as simple as:

foreach(key, value, ref dopurge; container)
{
   dopurge = checkIfDone(key, value);
}

One nice thing, you get effectively O(1) removal from non-node containers like arrays, and you can remove while iterating containers that may normally be impossible to remove from while iterating.

-Steve

Reply via email to