removing element from DList

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 5 10:01:14 PST 2012


On Monday, November 05, 2012 17:41:15 Jack Applegame wrote:
> How to get range for single just inserted element?
> 
> DList!int list;
> ...
> list.insertBack(5);
> auto r = ??? // get range for single last element
> ...
> list.insertBack(something);
> ...
> list.remove(r);

If you want to remove an element, do

auto range = find(list[], elem);
list.remove(take(range, 1));

Unfortunately, it looks like insert* makes the choice of returning the number 
of elements inserted instead of a range starting at the newly inserted element 
(C++ std::list returns an iterators pointing to that element, which seems a 
lot more useful to me). So, you can't easily get at a range to the most 
recently inserted element.

However, since you know that it's the last element, if you want to remove it, 
it's easy. Just use

list.removeBack();

If you want a range to the last element for something other than removing it, 
then you'd probably have to do something like

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

though that won't be the original range type. If you need that, you'd probably 
have to pop elements off until there's only one left (probably by saving before 
every pop and then returning the saved range when the range is empty).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list