best way to convert string array of floats to a float array

Stephen Jones siwenjo at gmail.com
Tue Jul 24 21:18:13 PDT 2012


On Wednesday, 25 July 2012 at 03:23:52 UTC, Jonathan M Davis 
wrote:
> On Wednesday, July 25, 2012 04:06:57 Stephen Jones wrote:
>> On Tuesday, 24 July 2012 at 02:05:18 UTC, Brad Anderson wrote:
>> > On Tuesday, 24 July 2012 at 02:03:40 UTC, Stephen Jones 
>> > wrote:
>> >> When it comes to reading float data from a text file into a
>> >> float array is there a better option than reading the data
>> >> into a string array and then stepping though the array and
>> >> converting the values into a float array:
>> >> 
>> >> string[] textData=read text data;
>> >> float[] f;
>> >> 
>> >> foreach(string s; textData){
>> >> 
>> >>    f~=to!(float)(s);
>> >> 
>> >> }
>> > 
>> > auto flist = textDataRange.map!(a => a.to!float).array();
>> 
>> Thanks Brad. This converts the string into an auto type, but I
>> need to dump the data in the auto into a float array:
>> 
>> auto f=map!(to!(float))(split(chompPrefix(s, "lno:")));
>> 
>> float[] dat;
>> dat~=f;
>> 
>> The above won't compile complaining that "Cannot append type
>> Result to type float[]"
>
> map returns a lazy range. If you want an array, pass the result 
> to
> std.array.array.
>
> - Jonathan M Davis

Thanks Jonathan. Very cool language this:

float[] dat;
dat~=array(map!(to!(float))(split(chompPrefix(s, "lno:"))));

The data is read from a string that contains floats, parsed by 
the split into an array, converted into an array of auto via the 
mapping with the to!float function, and then cast into the float 
array dat.

Longhand that data would be read into the program as a string, 
converted into an array of strings then converted into an array 
of floats and the initial string and the array of strings would 
both accumulate on the GC waiting list. Does the code above weed 
out some of the redundant data thereby reducing calls upon the GC?


More information about the Digitalmars-d-learn mailing list