2010-07-30 57 views
0

我想这是一个愚蠢的问题,但这是我的问题:HashMap:处理托管对象C++

我想要一个hash_map<int, Object^>作为我的对象BigObject的属性,它是用托管C++编写的。

所以我必须声明一个指针hash_map<int, Object^>* hash,因为我无法在托管代码中声明明确的本机对象。

如何插入对象? hash_map[]将无法使用指针,我不能使插入工作(我不能使用std::pair<int, Object^>,因为对象是管理...

非常感谢

回答

1

你应该声明你的HashMap为hash_map<int, gcroot<Object^> >。你会需要#include <vcclr.h>

参见msdn

编辑:添加代码示例

#include <iostream> 
#include <vcclr.h> 
#include <hash_map> 

using namespace std; 
using namespace stdext; 
using namespace System; 

int main() 
{ 
    hash_map<int, gcroot<Object^> > hash; 

    hash.insert(make_pair<int, gcroot<Object^> >(5, 
       gcnew String("hello world"))); 

    return 0; 
} 
+0

完美的作品。非常感谢 – ccote 2010-07-30 18:03:39

0

如果您在.NET中工作,为什么不使用.NET集合之一?它们可以直接在C++/CLI中使用,也可以与其他.NET语言共享,其中std::hash_map不能。他们和垃圾收集器很好地玩。

.NET提供了几个散列表实现,包括'System.Collections.HashTable'System.Collections.Generic.Dictionary

就你而言,Dictionary<int, Object^>^将是适当的。

+0

我想实际上使用multimap。一个词典只能将一个键指向一个正确的值? – ccote 2010-08-04 20:14:05

+0

在这种情况下,我通常使用'Dictionary >'。 – 2010-08-04 21:11:24

0
hash_map <double,gcroot<siteNEVObjectdic^>> d; 
d.insert(make_pair<double,gcroot<siteNEVObjectdic^>>(PN2,gcnew siteNEVObjectdic(Lat1,Long1,Lat2,Long2,Lat3,Long3))); 

这成为了一种魅力。