Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

collection iterator remove current element

Moderators: kris

Posted: 06/24/07 00:12:44 Modified: 06/24/07 00:32:32

Hi ! 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:


static class ArrayIterator(T) : AbstractIterator!(T)
private ArraySeq seq;

public this (ArraySeq seq)
this.seq = seq;

public final void remove()


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[]);
	/*auto it = strings.elements();
	while(it.more) {
		auto element = it.get;
		Stdout.formatln("now at: {}, remaining: {}", element, it.remaining);
		if( element == "bla" )
	foreach(element; strings.elements)
		if( element == "bla" )
	foreach(element; strings.elements())
		Stdout.formatln("{}", element);

Both the iterator approach (in comments), as well as the foreach are working.

What do you think ?

Author Message

Posted: 06/27/07 06:23:31

Nice going, Daniel

Can you do this cleanly for all containers? If so, the second step would be to expose the choice of mutation-checking or removal-support ... that could be done via another template argument, but we'd want to see something that's not too hard on the casual user?

The other thing we'd ultimately like to see is support for a configurable memory mgr in containers, instead of relying on the GC for everything. Perhaps that's for another day :)

- Kris