array of randomly generated names
Simen kjaeraas
simen.kjaras at gmail.com
Sat Oct 16 03:08:39 PDT 2010
spir <denis.spir at gmail.com> wrote:
> Oh, yes. You mean since the string data is immutable, there is no risk
> in sharing strings?
Exactly.
> Does this really mean (like lisp lists, for instance), that b really
> shares elements (chars) with a?
> (So that, if they were mutable instead, changing chars in b would then
> change a?)
Indeed.
> Right. I'll use dup, seems more self-commenting for me.
> By the way, is it possible to alias funcs/methods like types? (I'll
> try...). To me,
> "copy" would be far more obvious than "dup" ;-)
Sure you can alias functions. However, .dup is kinda special, so you'll
have to write a helper function for it:
T copy( T )( T arg ) {
return arg.dup;
}
>> auto names =new dchar[][](numNames, nameLength);
[snip]
> Is "auto" here used because it looks stupid to repeat the type, which is
> neccessary on right side?
Yup.
> Also, let's say names are dstrings (by casting once built) instead of
> dchar[]. Is it still possible to dimension names at startup? I mean, how
> to tell D the size of elements (names)?
Yes. This works:
char[] a;
a.length = size;
string b = cast(string)b;
One other good way to build strings is to use std.array's appender.
http://digitalmars.com/d/2.0/phobos/std_array#Appender
>> dchar[nameLength] name;
>> //...
>> names[i] = to!string(name[]); (since it's a static array in this case,
>> you have
>> to slice it to pass it to to!()).
>
> Hum, I'm not sure this works because nameLength is a variable,; or does
> it? (I'll try)
It shouldn't, no.
> It looks strange to me to define a static array from a variable length
> ;-)
> Is the memory allocation issue really relevant, since if it's not
> allocated for name, then it must be for names[i]?
Seems like the same cost, only different locations to me.
> Also, would idup work here, instead of (pseudo-)slicing? (I'll try this,
> too)
It would. The slicing is only used because Jonathan was assuming a to be
a static array.
> Right, later I'll see what D ranges are (only read evocation of them as
> of now). I suspect they are more or lass what is often called iterators
> in other languages (or cursors in Eiffel).
They're mostly a pair of iterators, thus safer than the single iterators
offered by other languages.
--
Simen
More information about the Digitalmars-d-learn
mailing list