开发者

Is there any generic vesion of HashTable?

I need a cl开发者_Python百科ass that will work like C++ std::map. More specifically, I need such a behavior:

map< string, vector<int> > my_map;

Is it possible?


A dictionary is I believe what you want:

Dictionary<String, int> dict = new Dictionary<String, int>();

dict.Add("key", 0);
Console.WriteLine(dict["key"]);

etc, etc

MSDN: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

You can specify more or less any type as the key/value type. Including another dictionary, an array, or whatever:

Dictionary<String, String[]> dict = new Dictionary<String, String[]>();

So here each element in the Dictionary points to an array of strings.

To implement what you require (with the vector int), you would require a List as the value type:

Dictionary<String, List<int>> dict = new Dictionary<String, List<int>>();

It is worth noting that a Dictionary has no predefined order, whereas std::map does. If order is important, you may want to use SortedDictionary instead, which is almost identical in usage, but sorts on the key. All depends if you plan to iterate over the dictionary really.

Note however that if you use a class you created as the key, you will need to properly override GetHashCode and Equals.


It depends what you really need. As it has been already said you get the lookup behaviour using System.Collections.Generic.Dictionary<Key, Value>, so the equivalent to std::map<string, std::vector<int> > would be (using System.Collections.Generic.List<int> as vectorequivalent):

Dictionary<string, List<int>> myDictionary = new Dictionary<string, List<int>>();
myDictionary.Add("a", new List<int>());

and so on Internally Dictionary uses a Hashtable, while std::map uses a Red-Black-Tree, so std::map is ordered, while Dictionary is unordered. If you need an ordered Dictionary (which would be more closely to std::map, you can use System.Collections.Generic.SortedDictionary<Key, Value>. The usage is mostly identical which that of Dictionary


Yes, the declaration you have written in the question is correct. It maps a string onto a vector of ints. However, std::map is backed by a Red-Black tree implementation, and your question suggests you want a hash-table. If you can use boost, you could try their implementation of unordered_map. This is part of the tr1 specification, and implements the map as a hash-table. The hash functions for standard types are already implemented in boost, so you wouldn't need to worry about this.

#include <boost/unordered_map.hpp>
...
boost::unordered_map<std::string, std::vector<int> > my_map;


If your goal is to replace map, then you want 'SortedDictionary', because that also implements a red-black tree. If you want a Hash Table, then Dictionary will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜