Search code examples
dictionaryvisual-c++c++-clistdmap

Converting C# Dictionary to C++ map


I am receiving a dictionary from a C# dll to C++/CLI code. I am trying to convert dictionary into std::map which will be further used by old C++ code. but I am not able to do. I have a function which is will take dictionary as parameter and return a map.

This is what I am trying to do-

std::map < std::wstring, std::map<int, int>> Convert(Dictionary<String^, Dictionary<int, int>^>^ myMap)
{
   std::map < std::wstring, std::map<int, int>> h_result;

   for (std::wstring& stringKey : myMap->Keys)
   {
       for (std::pair<int, int> intKey : (myMap->Values))
       {
           h_result.insert(stringKey, intKey);
       }
   }

return h_result;
}

I am getting error while iterating the values.

error:this range-based 'for' statement requires a suitable "begin" function and none was found

Can anybody tell what is the problem here? or if there is any better way to convert Dictionary^ into std::map, please do suggest me.

I am new with dictionary and std::map. please let me know if there is any silly mistake with the sample code.


Solution

  • You're (a) trying to use C++ range-for loops with Dictionary^, and (b) trying to use System types interchangeably with C++ standard types. All of which won't work.

    You need to do this a bit more step-by-step: iterate the Dictionary^ collections with for each, convert the String^ to std::wstring properly, and create the map items with std::make_pair.

    So your function will look something like this (untested)

    std::map <std::wstring, std::map<int, int>> Convert(Dictionary<String ^, Dictionary<int, int>^> ^myMap)
    {
        std::map <std::wstring, std::map<int, int>> h_result;
    
        // iterate the outer dictionary
        for each(KeyValuePair<String ^, Dictionary<int, int>^> ^kvp1 in myMap)
            {
            std::wstring stringKey = marshal_as<std::wstring>(kvp1->Key);
    
            std::map<int, int> mapValues;
    
            // iterate the inner dictionary
            for each(KeyValuePair<int, int> ^kvp2 in kvp1->Value)
                {
                // insert in inner map
                mapValues.insert(std::make_pair(kvp2->Key, kvp2->Value));
                }
    
            // insert in outer map
            h_result.insert(std::make_pair(stringKey, mapValues));
            }
    
        return h_result;
    }