www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to filter an array so the result is an array again?

reply Cheng Wei <rivercheng gmail.com> writes:
The standard library std.algorithm is based on Range. So if
a = [1, 2, 3, 4];
auto r = filter!("a < 2")(a);

Here, r is a range.
How about I want an new array? Is there any easy way to convert the
result to array?

If we have to do like:
int[] b;
for (v; r) {
    b ~= v;
}

Then maybe it is easier to not use filter at all as:
int [] b;
for (v; a) {
   if (v < 2) b ~= v;
}

Thanks a lot.
Sep 15 2011
next sibling parent Cheng Wei <rivercheng gmail.com> writes:
Sorry, the 'for' should be 'foreach'.
Sep 15 2011
prev sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Friday, September 16, 2011 04:04:39 Cheng Wei wrote:
 The standard library std.algorithm is based on Range. So if
 a = [1, 2, 3, 4];
 auto r = filter!("a < 2")(a);
 
 Here, r is a range.
 How about I want an new array? Is there any easy way to convert the
 result to array?
 
 If we have to do like:
 int[] b;
 for (v; r) {
     b ~= v;
 }
 
 Then maybe it is easier to not use filter at all as:
 int [] b;
 for (v; a) {
    if (v < 2) b ~= v;
 }
Use std.array.array. auto a = [1, 2, 3, 4]; auto r = array(filter!"a < 2"(a)); - Jonathan M Davis
Sep 15 2011