C#等价于C ++ map <string,double> </string,double>

时间:2009-10-21 00:19:57

标签: c# arrays hashmap

我想为不同的帐户保留一些总计。在C ++中我会像这样使用STL:

map<string,double> accounts;

// Add some amounts to some accounts.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

cout << "Fred owes me $" << accounts['Fred'] << endl;

现在,我将如何在C#中做同样的事情?

8 个答案:

答案 0 :(得分:79)

大致为: -

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

答案 1 :(得分:16)

Dictionary<string, double> accounts;

答案 2 :(得分:11)

虽然System.Collections.Generic.Dictionary匹配标记“hashmap”并且在您的示例中运行良好,但它并不完全等同于C ++的std :: map - std :: map是一个有序集合。

如果订购很重要,您应该使用SortedDictionary

答案 3 :(得分:4)

你想要Dictionary类。

答案 4 :(得分:2)

字典是最常见的,但您可以使用其他类型的集合,例如 System.Collections.Generic.SynchronizedKeyedCollection,System.Collections.Hashtable或任何KeyValuePair集合

答案 5 :(得分:2)

此代码就是您所需要的:

   static void Main(string[] args) {
        String xml = @"
            <transactions>
                <transaction name=""Fred"" amount=""5,20"" />
                <transaction name=""John"" amount=""10,00"" />
                <transaction name=""Fred"" amount=""3,00"" />
            </transactions>";

        XDocument xmlDocument = XDocument.Parse(xml);

        var query = from x in xmlDocument.Descendants("transaction")
                    group x by x.Attribute("name").Value into g
                    select new { Name = g.Key, Amount = g.Sum(t => Decimal.Parse(t.Attribute("amount").Value)) };

        foreach (var item in query) {
            Console.WriteLine("Name: {0}; Amount: {1:C};", item.Name, item.Amount);
        }
    }

内容是:

姓名:弗雷德;金额:8,20雷亚尔;
姓名:约翰;金额:R $ 10,00;

这是在C#中以声明方式执行此操作的方式!

我希望这有帮助,

Ricardo Lacerda Castelo Branco

答案 6 :(得分:1)

虽然我们在讨论STL,地图和字典,但我建议您查看C5库。它提供了我经常发现有用的几种类型的词典和地图(以及许多其他有趣和有用的数据结构)。

如果你像我一样转向C#的C ++程序员,你会发现这个库是一个很好的资源(以及这个字典的数据结构)。

-Paul

答案 7 :(得分:0)

C ++ std::map<>(内部树)最接近的等价物是C#OrderedDictionary<>(内部树),而C#OrderedDictionary<>缺少一些来自C ++的非常重要的方法{{1} },即:std::map<>std::map::findstd::map::lower_boundstd::map::upper_boundstd::map::equal_range std::map,它们基本上是前4种方法的主干

为什么这4种方法很重要?因为它使我们能够找到给定键的“行踪”,除了只能检查键是否存在,或者保证SortedDictionary被订购。

iterators中某个键的“行踪”是什么?密钥不一定必须存在于集合中,我们想知道密钥可能位于的位置,通常在两个迭代器之间分别指向集合中的两个相邻的现有密钥,因此我们可以在范围内操作密钥属于std::map复杂度。如果没有这样的4个方法(使用迭代器),每次针对密钥查询范围时,都必须对集合进行O(logN)迭代。