C# equivalent of C++ map<string,double>
Solution 1
Roughly:-
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"]);
Solution 2
Dictionary<string, double> accounts;
Solution 3
Although System.Collections.Generic.Dictionary matches the tag "hashmap" and will work well in your example, it is not an exact equivalent of C++'s std::map - std::map is an ordered collection.
If ordering is important you should use SortedDictionary.
Solution 4
You want the Dictionary class.
Solution 5
Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection
Related videos on Youtube
Adam Pierce
I'm a programmer, why else would I be here ? I do C++ mostly under Windows and Linux. I'm also not half bad at electronics design, microcontrollers and programmable logic devices such a FPGAs. I am available for freelance work from time to time, contact me via my blog at siliconsparrow.com.
Updated on July 05, 2022Comments
-
Adam Pierce about 2 years
I want to keep some totals for different accounts. In C++ I'd use STL like this:
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;
Now, how would I do the same thing in C# ?
-
Adam Pierce over 14 yearsThis is very close to what I need, the only drawback is I do not know what the names of the accounts will be ahead of time.
-
XXXXX over 14 yearsYou don't need to know them ahead of time. The examples use constant strings for brevity, but you can use string objects.
-
Adam Pierce over 14 yearsPerhaps I should clarify that comment by saying "I do not know the names, or how many names I will have". In this answer, if I added accounts["Ron"] += 2.50;, it would throw an exception. In reality, I'll be throwing an XML file at it with lots of names and numbers.
-
Adam Pierce over 14 yearsWell, I've already done it with Dictionary now but the XML is real simple, just a list of tags like this: <transaction name="Fred" amount="5.20" />
-
Alastair Pitts over 14 yearsActually no, if you use the index and attempt to set a non-existent key, it will actually create the object for you with the specified key. An exception will only be thrown on the get operation. Look here on remarks: msdn.microsoft.com/en-us/library/9tee9ht2.aspx
-
XXXXX over 14 yearsErebus is correct: You can arbitrarily add things to a Dictionary without knowing at compile time what or how many elements will be in the dictionary.
-
Alex about 11 yearsWhy people so much like
var
? -
DarkWanderer over 10 years@Alex: because var is much shorter than IParallelEnumerable<Record<string,XmlSerializer>> :)
-
Kevin Depue about 10 yearsDictionaries in c# are not equivalent to stl::map's just so you know - c# dictionaries are hash tables whereas stl::map's are red-black trees, the underlying algorithms are totally different.
-
Marcus Mangelsdorf over 8 yearsNote, that the
accounts["Fred"] = 0;
in this example is equivalent toaccounts.Add("Fred", 0);
(See dotnetfiddle.net/q3UteL for both variants) Also: *When you useDictionary.Add( Key, Value )
to add a newKeyValuePair
anArgumentException
will be thrown if theKey
already exists in the dictionary. *Using the indexer (Dictionary[ Key ]
) you get an implicit add-or-update behavior since theKey
will automatically be added if it is not contained in the Dictionary already otherwise the corresponding value will simply be updated. *Consider using decimal for currency