DList -- removing an element

Jonathan M Davis jmdavisProg at gmx.com
Sun Dec 30 02:46:43 PST 2012


On Sunday, December 30, 2012 15:59:01 d coder wrote:
> Greetings
> 
> I have created a DList of class objects. Now I want to delete a particular
> object from the list. I do not see a straightforward way of doing that. The
> only way I found was to create a DList range, take out all other elements
> from the range using popFront and popBack and then apply remove(Range).
> 
> Am I missing something?

You should be able to do something like

list.stableRemove(take(find(list[], 5), 3));

or if you prefer UFCS

list.stableRemove(list[].find(5).take(3));

A more detailed example would be

import std.algorithm;
import std.container;
import std.range;
import std.stdio;

void main()
{
    auto list = make!(DList!int)([2, 9, 14, 22, 7, 64, 5]);
    assert(equal(list[], [2, 9, 14, 22, 7, 64, 5]));

    auto found = find(list[], 14);
    assert(equal(found, [14, 22, 7, 64, 5]));

    auto toRemove = take(found, 3);
    assert(equal(toRemove, [14, 22, 7]));

    list.linearRemove(toRemove);
    assert(equal(list[], [2, 9, 64, 5]));
}

For some reason, DList's remove function won't accept the result of take, so 
you have to use linearRemove. But in general, the functions in std.container 
which take the range type of the container that the function is on should 
accept the result of take, takeExactly, and takeOne. If they don't (and some 
don't yet), then it's a bug. And the remove functions generally take the range 
type of their container, so you use find to find the element that you want and 
one of the take functions to create a range with only the elements that you 
want to remove rather than every element starting at the element that you were 
searching for.

- Jonathan M Davis


P.S. This sort of question really should be asked in D.Learn. This newsgroup 
is for general discussions about the language, not for questions on how to use 
aspects of the language or the standard library.


More information about the Digitalmars-d mailing list