code

C ++ 맵에 해당하는 C #

codestyles 2020. 12. 4. 08:13
반응형

C ++ 맵에 해당하는 C #


다른 계정에 대한 일부 합계를 유지하고 싶습니다. 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 #에서 어떻게 똑같은 일을 할 수 있습니까?


대충:-

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"]);

Dictionary<string, double> accounts;

System.Collections.Generic.Dictionary가 "hashmap"태그와 일치하고 예제에서 잘 작동하지만 C ++의 std :: map과 정확히 일치하지는 않습니다. std :: map은 정렬 된 컬렉션입니다.

순서가 중요한 경우 SortedDictionary 를 사용해야합니다 .


당신은 원하는 사전 클래스를.


사전이 가장 일반적이지만 System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable 또는 모든 KeyValuePair 컬렉션과 같은 다른 유형의 컬렉션을 사용할 수 있습니다.


이 코드 만 있으면됩니다.

   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);
        }
    }

내용은 다음과 같습니다.

이름 : Fred; 금액 : R $ 8,20;
이름 : John; 금액 : R $ 10,00;

That is the way of doing this in C# - in a declarative way!

I hope this helps,

Ricardo Lacerda Castelo Branco


While we are talking about STL, maps and dictionary, I'd recommend taking a look at the C5 library. It offers several types of dictionaries and maps that I've frequently found useful (along with many other interesting and useful data structures).

If you are a C++ programmer moving to C# as I did, you'll find this library a great resource (and a data structure for this dictionary).

-Paul


The closest equivalent of C++ std::map<> (a tree internally) is C# OrderedDictionary<> (a tree internally), while C# OrderedDictionary<> is missing some very important methods from C++ std::map<>, namely: std::map::find, std::map::lower_bound, std::map::upper_bound, std::map::equal_range, and std::map iterators, which are basically the backbone for the previous 4 methods.

Why those 4 methods are important? Because it gives us the ability to locate the "whereabouts" of a given key, in addition to only being able to check if a key exists, or the SortedDictionary is guaranteed to be ordered.

What is "whereabouts" of a key in a std::map? The key doesn't necessarily have to exist in the collection, we want to know the location the key might be at, usually between two iterators pointing to two adjacent existing keys respectively in the collection, so we can operate on the range the key falls into in a O(logN) complexity. Without such 4 methods (with iterators), one has to do an O(N) iteration through the collection every time a range is queried against a key.

참고URL : https://stackoverflow.com/questions/1598070/c-sharp-equivalent-of-c-mapstring-double

반응형