Cpp / Cli将std :: map转换为.net字典

时间:2012-03-29 07:32:42

标签: c++ dictionary map command-line-interface

我有一个cpp项目,一个c ++ cli项目和一个c#win表单项目。我的本机cpp项目中有一个std :: map。如何在我的cli项目中将其转换为.net字典?

1 个答案:

答案 0 :(得分:6)

//Assuming dictionary of int/int:
#include <map>

#pragma managed

using namespace System::Collections::Generic;
using namespace std;

/// <summary>
/// Converts an STL int map keyed on ints to a Dictionary.
/// </summary>
/// <param name="myMap">Pointer to STL map.</param>
/// <returns>Dictionary of int keyed by an int.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="myMap"/> parameter was a NULL pointer.    
Dictionary<int, int>^ Convert(map<int, int>* myMap)
{ 
  if (!myMap)
    throw gcnew System::ArgumentNullException("myMap");

  Dictionary<int, int>^ h_result = gcnew Dictionary<int, int>(myMap->size());

  for (pair<int, int> kvp : *myMap)
  {
     h_result->Add(kvp.first, kvp.second);
  }

  return h_result;
}