Forum Navigation
collection iterator remove current element
Moderators:
kris
Posted: 06/24/07 00:12:44 Modified: 06/24/07 00:32:32Hi ! Of course one should not directly remove various elements from a collection while iterating over it. But what about removing the current element by using an iterator? This seems to be safe, so why not give it a try:
I tried it with ArraySeq? and got it working:
tango.util.collection.ArraySeq?
static class ArrayIterator(T) : AbstractIterator!(T) { ... private ArraySeq seq; public this (ArraySeq seq) { ... this.seq = seq; } public final void remove() { seq.removeAt(--row); }
tango.util.collection.model.Iterator
public interface Iterator(V) { ... public void remove(); }But I had to remove the mutation checks.
Now it's working fine, like:
auto strings = new ArraySeq!(char[]); strings.append("test"); strings.append("bla"); strings.append("foo"); /*auto it = strings.elements(); while(it.more) { auto element = it.get; Stdout.formatln("now at: {}, remaining: {}", element, it.remaining); if( element == "bla" ) it.remove; }*/ foreach(element; strings.elements) if( element == "bla" ) strings.remove(element); foreach(element; strings.elements()) Stdout.formatln("{}", element);
Both the iterator approach (in comments), as well as the foreach are working.
What do you think ?