www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Best way to duplicate an associative array

reply Paolo Invernizzi <arathorn NOSPAM_fastwebnet.it> writes:
Hi all,

As the subject, there's a way to easy to .dup and associative array?

Thanks

---
Paolo Invernizzi
Mar 23 2006
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Paolo Invernizzi" <arathorn NOSPAM_fastwebnet.it> wrote in message 
news:dvu0oj$qbo$1 digitaldaemon.com...
 Hi all,

 As the subject, there's a way to easy to .dup and associative array?

 Thanks

template dup(T) { T dup(T aa) { auto keys = aa.keys; T aa2; foreach(key; keys) aa2[key] = aa[key]; return aa2; } } void main() { int[char[]] aa; aa["hello"] = 5; aa["fork"] = 10; int[char[]] aa2 = aa.dup(); foreach(char[] key, int value; aa) writefln(key, ": ", value); writefln(); foreach(char[] key, int value; aa2) writefln(key, ": ", value); } Try that on for size :)
Mar 23 2006
next sibling parent reply =?ISO-8859-1?Q?Anders_F_Bj=F6rklund?= <afb algonet.se> writes:
Jarrett Billingsley wrote:

As the subject, there's a way to easy to .dup and associative array?


 Try that on for size :) 

tmp.d:9: no identifier for declarator key Guess it requires DMD 0.148 or better... --anders
Mar 23 2006
parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Anders F Björklund" <afb algonet.se> wrote in message 
news:dvubug$19r4$1 digitaldaemon.com...
 Jarrett Billingsley wrote:

As the subject, there's a way to easy to .dup and associative array?


 Try that on for size :)

tmp.d:9: no identifier for declarator key Guess it requires DMD 0.148 or better...

Indeed it does, as it also requires IFTI. SO I guess 0.149 is the minimum.
Mar 23 2006
prev sibling parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Jarrett Billingsley" <kb3ctd2 yahoo.com> wrote in message 
news:dvuba7$196f$1 digitaldaemon.com...

Actually, this is simpler and may be faster (not sure):

template dup(T)
{
 T dup(T aa)
 {
  T aa2;

  foreach(key, value; aa)
   aa2[key] = value;

  return aa2;
 }
}

void main()
{
 int[char[]] aa;
 aa["hello"] = 5;
 aa["fork"] = 10;

 int[char[]] aa2 = aa.dup();

 foreach(char[] key, int value; aa)
  writefln(key, ": ", value);

 writefln();

 foreach(char[] key, int value; aa2)
  writefln(key, ": ", value);
} 
Mar 23 2006
parent pragma <pragma_member pathlink.com> writes:
In article <dvufh2$1e9l$1 digitaldaemon.com>, Jarrett Billingsley says...
"Jarrett Billingsley" <kb3ctd2 yahoo.com> wrote in message 
news:dvuba7$196f$1 digitaldaemon.com...

Actually, this is simpler and may be faster (not sure):

template dup(T)
{
 T dup(T aa)
 {
  T aa2;

  foreach(key, value; aa)
   aa2[key] = value;

  return aa2;
 }
}

Its likely faster as you're not performing a lookup on 'aa' twice per loop. - EricAnderton at yahoo
Mar 23 2006