Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

hashmap

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# ?

like image 400
Adam Pierce Avatar asked Oct 21 '09 00:10

Adam Pierce


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.


4 Answers

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"]); 
like image 188
ljs Avatar answered Sep 30 '22 00:09

ljs


Dictionary<string, double> accounts; 
like image 23
Daniel A. White Avatar answered Sep 30 '22 00:09

Daniel A. White


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.

like image 45
user200783 Avatar answered Sep 30 '22 00:09

user200783


You want the Dictionary class.

like image 41
Daniel Pryden Avatar answered Sep 29 '22 23:09

Daniel Pryden