www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to remove element from an SList?

reply "Chris Pons" <cmpons gmail.com> writes:
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 );
Mar 27 2012
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 03/27/2012 05:02 PM, Chris Pons 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 don't have experience with std.container but I think you need to call take(a, 1).
 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 following worked for me. Note treating the SList as a range by []: import std.container; import std.stdio; import std.algorithm; import std.range; void main() { auto l = SList!int(1, 2, 3, 4, 5, 6, 7); auto a = find(l[], 2); // Search for 2 ... l.linearRemove(take(a, 1)); // ... and remove just 2 auto b = find(l[], 6); // Search for 6 ... l.linearRemove(b); // ... and remove from there assert(l == SList!int(1, 3, 4, 5)); } Ali
Mar 27 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
Ali Çehreli:

 The following worked for me. Note treating the SList as a range 
 by []:

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

 void main()
 {
     auto l = SList!int(1, 2, 3, 4, 5, 6, 7);

     auto a = find(l[], 2);      // Search for 2 ...
     l.linearRemove(take(a, 1)); // ... and remove just 2

     auto b = find(l[], 6);      // Search for 6 ...
     l.linearRemove(b);          // ... and remove from there

     assert(l == SList!int(1, 3, 4, 5));
 }
That seems an example for the dlang site docs :-) (It just needs to show the usage of "cursors" to on the list?) Bye, bearophile
Mar 27 2012