How to remove element from an SList?

James Miller james at aatch.net
Tue Mar 27 18:00:16 PDT 2012


On 28 March 2012 13:02, Chris Pons <cmpons at gmail.com> wrote:
> Right now i'm struggling with trying to understand how to remove an element
> from a n SList. I only want to remove one element, not a range of elements.
> I also don't want to use an Array because I will have to reshuffle elements
> to take care of the empty spot when I remove it.
>
> The only thing I've seen so far is find from std. algorithm and
> linearRemove. However I can't get find to work and I don't exactly believe
> linearRemove will work either because afaik that removes up to the index
> specified? I'm not to clear on this.
>
> Here's a simplified example of what I was trying:
>
> SList!int intList;
> intList.insert( 1 );
> auto a = find( intList, 1 );
> intList.linearRemove( a );

The documentation is very unclear, I had to figure out what
linearRemove did from the unittest for it.

This example (comments are mine) should help:

    auto s = SList!int(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    auto r = s[]; // Slice of the original list
    popFrontN(r, 3); // Removes the first 3 elements
    auto r1 = take(r, 4); // returns the first 4 elements
    assert(equal(r1, [4, 5, 6, 7]));
    auto r2 = s.linearRemove(r1); //removes the range [4,5,6,7]
    assert(s == SList!int(1, 2, 3, 8, 9, 10));
    assert(equal(r2, [8, 9, 10]));

The docs mention that the range you use to remove, should be sourced
from the original list. Also, you actually need to use take(), since
the only to remove from the middle is with a Take!Range, its not very
clear, or understandable, but that's the way you have to do it.

Also, you are right the the other linearRemove does remove upto the
element, however, it works by again, passing a range.

std.containers is an odd beast, and I might do some more
investigation. However, all you need to know is that in order to
remove, say the 5th element from a SList, you need to do this:

    SList!int s = [1,2,3,4,5,6,7,8,9,0];
    auto r = s[0..4];
    auto r1 = take(1, r);
    s.linearRemove(r1)

Not the most intuitive way in the world...

--
James Miller


More information about the Digitalmars-d-learn mailing list