HashMap:处理托管对象C ++

时间:2010-07-30 15:32:10

标签: c++-cli hashtable

我想这是一个愚蠢的问题,但这是我的问题:

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

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

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

非常感谢

3 个答案:

答案 0 :(得分:1)

您应该将哈希地图声明为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;
}

答案 1 :(得分:0)

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

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

在您的情况下,Dictionary<int, Object^>^是合适的。

答案 2 :(得分:0)

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

这是一种魅力。