C# equivalent of C++ map<string,double>

174,564

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

Share:
174,564

Related videos on Youtube

Adam Pierce
Author by

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, 2022

Comments

  • Adam Pierce
    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
    Adam Pierce over 14 years
    This 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
    XXXXX over 14 years
    You don't need to know them ahead of time. The examples use constant strings for brevity, but you can use string objects.
  • Adam Pierce
    Adam Pierce over 14 years
    Perhaps 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
    Adam Pierce over 14 years
    Well, 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
    Alastair Pitts over 14 years
    Actually 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
    XXXXX over 14 years
    Erebus 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
    Alex about 11 years
    Why people so much like var?
  • DarkWanderer
    DarkWanderer over 10 years
    @Alex: because var is much shorter than IParallelEnumerable<Record<string,XmlSerializer>> :)
  • Kevin Depue
    Kevin Depue about 10 years
    Dictionaries 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
    Marcus Mangelsdorf over 8 years
    Note, that the accounts["Fred"] = 0;in this example is equivalent to accounts.Add("Fred", 0); (See dotnetfiddle.net/q3UteL for both variants) Also: *When you use Dictionary.Add( Key, Value ) to add a new KeyValuePair an ArgumentException will be thrown if the Key already exists in the dictionary. *Using the indexer (Dictionary[ Key ]) you get an implicit add-or-update behavior since the Key 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