string-int[] array

Baz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 8 12:05:31 PDT 2015


On Sunday, 8 March 2015 at 18:54:43 UTC, Meta wrote:
> On Sunday, 8 March 2015 at 18:38:02 UTC, Dennis Ritchie wrote:
>> On Sunday, 8 March 2015 at 18:18:15 UTC, Baz wrote:
>>> import std.stdio;
>>> import std.typecons;
>>>
>>> alias T = Tuple!(string, int);
>>>
>>> void main(string[] args)
>>> {
>>>   T[] tarr;
>>>   tarr ~= T("a",65);
>>>   tarr ~= T("b",66);
>>>   writeln(tarr);
>>> }
>>> ----
>>>
>>>> [Tuple!(string, int)("a", 65), Tuple!(string, int)("b", 66)]
>>
>> Thanks, will do.
>
> It might be better to use std.variant.Algebraic. An array of 
> tuples is wasteful of memory as you only need one or the other.
>
> import std.variant;
>
> alias IntOrStr = Algebraic!(int, string);
>
> IntOrStr[] makeIntOrStrArray(T...)(T vals)
> {
> 	import std.algorithm;
> 	import std.array;
> 	
> 	auto result = new IntOrStr[](T.length);
> 	foreach (i, val; vals)
> 	{
> 		result[i] = IntOrStr(val);
> 	}
> 	
> 	return result;
> }
>
> void main()
> {
> 	IntOrStr[] arr = makeIntOrStrArray(4, "five");
> }

Yes, but the tuple is used here because i misunderstood the 
question, cf my own answer to my first answer, anyway, never mind.


More information about the Digitalmars-d-learn mailing list