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

Ada*_*rce 61 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;
Run Code Online (Sandbox Code Playgroud)

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

ljs*_*ljs 85

大致:-

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"]);
Run Code Online (Sandbox Code Playgroud)

  • c#中的字典不等同于stl :: map,所以你知道 - c#字典是哈希表,而stl :: map是红黑树,底层算法完全不同. (7认同)
  • 实际上不,如果您使用索引并尝试设置不存在的键,它实际上将使用指定的键为您创建对象.只会在get操作上抛出异常.请看这里的评论:http://msdn.microsoft.com/en-us/library/9tee9ht2.aspx (4认同)
  • 注意,`accounts ["Fred"] = 0;`在这个例子中`相当于`accounts.Add("Fred",0);`(参见https://dotnetfiddle.net/q3UteL两种变体) :*当你使用`Dictionary.Add(Key,Value)`来添加一个新的`KeyValuePair`时,如果字典中已经存在`Key`,那么将抛出**'ArgumentException`**.*使用索引器(`Dictionary [Key]`)你会得到一个隐含的**add-or-update**行为,因为如果它没有包含在Dictionary中,它会自动添加`Key`,否则相应的值将只是得到更新.*考虑使用十进制货币 (3认同)

Dan*_*ite 17

Dictionary<string, double> accounts;
Run Code Online (Sandbox Code Playgroud)


use*_*783 14

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

如果排序很重要,您应该使用SortedDictionary.


Dan*_*den 6

你想要Dictionary类。