We need to rethink remove in std.container

Jonathan M Davis jmdavisProg at gmx.com
Mon Feb 21 22:08:13 PST 2011


On Monday 21 February 2011 21:51:51 %u wrote:
> You know, I'm actually now questioning whether STL did the right thing
> with requiring iterators for the erase() method. It actually seems
> quite pointless -- there's no reason why integer indices wouldn't
> work. I don't think we really need to follow suit with STL here... is
> there some situation with erase() that I'm missing that can't be
> covered with plain integer (or rather, size_t) indices, and that
> requires ranges?

Some of them do take indices, but you can't generally operate on indices. To do 
that, you need the original container. But you can operate on an iterate just 
fine. So, it's generally easier to deal with iterators.

However, the big thing would be that it actually doesn't make sense to use 
indices in many cases. Think about RedBlackTree for a moment. If you remove 
something from it or add something to it, that doesn't invalidate any range that 
you have which points to it (assuming that the end points haven't changed). You 
can still take that range and use it any any algorithm that you want - including 
remove (assuming that the algorithm takes the appropriate kind of range of 
course), and it will work. But using indices wouldn't work. They would have 
changed. Adding or removing anything to a container at or before an index that 
you have would make it so that that index no longer points to the same element. 
However, for many containers (though not all), any iterators or ranges would 
still be valid.

So, on the whole, using iterators or ranges makes great sense. I have no problem 
with how the STL does that. The problem is transitioning that to ranges. The STL 
doesn't go and change your iterator types on you when you feed them to 
algorithms, but std.range and std.algorithm typically do. So, the result is sub-
optimal in this case, to say the least.

- Jonathan M Davis


More information about the Digitalmars-d mailing list