removing element from DList

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 5 13:34:46 PST 2012


On Monday, November 05, 2012 21:59:05 Jack Applegame wrote:
> On Monday, 5 November 2012 at 19:31:25 UTC, Jonathan M Davis
> 
> wrote:
> > If all you want is the
> > last element, then use list[].back, since DList's range is
> > bidirectional.
> > 
> > - Jonathan M Davis
> 
> No. I want after inserting element, remember its "position" (in
> C++ I used iterator) and remove it later even if other elements
> was inserted after it.

If you're using insertBack like you're original post lists, then you know that 
it's at the back. However, unfortunately, DList made the choice of returning 
the number of elements inserted rather than a range starting at the element 
inserted, so if you want a range to that element, you're either going to have 
to do

auto range = retro(take(retro(list[]), 1));

or

typeof(list[]) targetRange = list[];

for(auto range = list[]; list.empty; list.popFront())
 targetRange = range.save;

The first is obviously more efficient, but it won't give you the same type as 
list[] (whether that matters depends on what you're doing). The second will 
given you the correct type but is obviously suboptimal and only works because 
you know that you inserted it at the end. If you were inserting in the middle 
somewhere, you'd have to use find to find the new element (which could be 
problematic if the list contains duplicates), or you'd have to somehow know 
how deep into the list the element is and pop that many elements from list[].

Personally, I think that it was a serious mistake for insert* to not return a 
range like C++ returns an iterator, but at least for the moment, that's what 
it does. The basic design for std.container is solid, but a number of the 
details definitely need some work, particularly since this is the first major 
attempt to have containers using ranges exclusively without anything like an 
iterator, and it's one area where ranges aren't always better than iterators.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list