0

C ++ std::mapのように機能するクラスが必要です。より具体的には、私はそのような行動が必要です:
map< string, vector<int> > my_map;
それは可能ですか?

4

4 に答える 4

12

辞書はあなたが欲しいものを信じています:

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

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

などなど

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

キー/値タイプとして、多かれ少なかれ任意のタイプを指定できます。別の辞書、配列、またはその他のものを含める:

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

したがって、ここでは、ディクショナリの各要素が文字列の配列を指しています。

必要なものを(ベクトルintを使用して)実装するには、値の型としてリストが必要になります。

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

std :: mapには事前定義された順序があるのに対し、辞書には事前定義された順序がないことに注意してください。順序が重要な場合は、代わりにSortedDictionaryを使用することをお勧めします。これは、使用法はほとんど同じですが、キーで並べ替えます。あなたが本当に辞書を反復することを計画するかどうかはすべてに依存します。

ただし、キーとして作成したクラスを使用する場合は、GetHashCodeとEqualsを適切にオーバーライドする必要があることに注意してください。

于 2009-12-16T13:19:11.920 に答える
1

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

于 2009-12-16T13:39:39.430 に答える
0

はい、質問に書いた宣言は正しいです。文字列をintのベクトルにマップします。ただし、std :: mapは赤黒木実装に支えられており、あなたの質問はハッシュテーブルが必要であることを示唆しています。boostを使用できる場合は、unordered_mapの実装を試すことができます。これはtr1仕様の一部であり、マップをハッシュテーブルとして実装します。標準型のハッシュ関数はすでにboostに実装されているので、これについて心配する必要はありません。

#include <boost/unordered_map.hpp>
...
boost::unordered_map<std::string, std::vector<int> > my_map;
于 2009-12-16T13:24:41.470 に答える
0

マップを置き換えることが目標の場合は、「SortedDictionary」が必要です。これは、赤黒木も実装しているためです。ハッシュテーブルが必要な場合は、ディクショナリが機能します。

于 2009-12-16T14:13:35.290 に答える