A slice consisting of non-consecutive elements of an array?

vit vit at vit.vit
Wed Jan 12 06:16:49 UTC 2022


On Wednesday, 12 January 2022 at 05:27:08 UTC, forkit wrote:
> I am familiar with the concept of a slice in D.
>
> However, a slice is a consecutive slice, is in not? (e.g) 
> [4..$-1]
>
> I would like a slice (or a view, or whatever name you wanna 
> call it), of particular elements within an array that may not 
> be consecutive. e.g. [4-7,8,10,13-16]
>
> Consider below:
>
> I want a slice/view on this array that only contains elements 
> with the string "one".
>
> ["one", "one", "two", "one", "two", "one", "one", "two]
>
> Most importantly, I do NOT want to allocate - so the slice/view 
> needs to be 'referencing'  existing data (not copying it).
>
> Yes, I can hard code it, C style. I already know this.
>
> Does phobos offer something like this?

Yes std.algorithm : filter.

```d
import std.stdio : writeln;
import std.algorithm : filter;

     void main()@safe{
         auto a = ["one", "one", "two", "one", "two", "one", 
"one", "two"];

     	writeln(a);
     	writeln(a.filter!(x => x == "one"));
     }
     ```


More information about the Digitalmars-d-learn mailing list