Here is how one might achive the same thing in C++. The syntax will improve with the advent of Lambda expressions in C++09 spec. These remind me of Perl's map and stack ($_) idioms.my %hash; $hash{A}{A} = 1; $hash{A}{B} = 2; $hash{B}{A} = 4; $hash{B}{B} = 8; foreach my $k (keys %{$hash{B}}) { print "$k - $hash{B}{$k}\n"; }
I was a little surprised to find C# does not make it very easy to use multidimensional hash tables. A few more seasoned C# programmers suggested using Generics. What is particularly unfriendly is the need to allocate and cast nested Hashtables. Perhaps, this is something Microsoft might fix in .NET version 4?#include <map> #include <string> #include <iostream> using namespace std; void main() { map<string, map<string, int>> hash; hash["A"]["A"] = 1; hash["A"]["B"] = 2; hash["B"]["A"] = 4; hash["B"]["B"] = 8; for(map<string, int>::iterator i = hash["B"].begin(); i != hash["B +"].end(); i++) { cout << i->first << " - " << i->second << "\n"; } }
Interestingly, Perl 6 only improves on version 5 slightly: -using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Hashtable hash = new Hashtable(); hash.Add("A", new Hashtable()); ((Hashtable)hash["A"]).Add("A", 1); ((Hashtable)hash["A"]).Add("B", 2); hash.Add("B", new Hashtable()); ((Hashtable)hash["B"]).Add("A", 4); ((Hashtable)hash["B"]).Add("B", 8); foreach (string k in ((Hashtable) hash["B"]).Keys) { Console.WriteLine(k + " - " + ((Hashtable) hash["B"])[ +k]); } } } }
Update: There is an alternative way in C# using the Dictionary template. This does away with the need to cast.my %hash; %hash{"A"}{"A"} = 1; %hash{"A"}{"B"} = 2; %hash{"B"}{"A"} = 4; %hash{"B"}{"B"} = 8; for %hash{"B"}.kv -> $key, $value { say "$key - $value" }
using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Dictionary<string, Dictionary<string, int>> hash2 = new Di +ctionary<string,Dictionary<string,int>>(); hash2.Add("A", new Dictionary<string, int>()); hash2["A"].Add("A", 1); hash2["A"].Add("B", 2); hash2.Add("B", new Dictionary<string, int>()); hash2["B"].Add("A", 4); hash2["B"].Add("B", 8); foreach (string k in hash2["B"].Keys) { Console.WriteLine(k + " - " + hash2["B"][k]); } } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Multidimesional hashs in Perl, C++, C# and Perl6
by duff (Parson) on May 04, 2007 at 13:59 UTC | |
|
Re: Multidimesional hashs in Perl, C++, C# and Perl6
by TedYoung (Deacon) on May 04, 2007 at 13:51 UTC | |
|
Re: Multidimesional hashs in Perl, C++, C# and Perl6
by parv (Parson) on May 04, 2007 at 20:32 UTC | |
by Util (Priest) on May 10, 2007 at 20:46 UTC |