Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Insert to map in map

How can I insert another map into the map?

In the code I try to copy the map from another.

multimap<string, map<size_t, size_t>> sorted;

for (auto itr=m_Items.begin(); itr !=m_Items.end(); ++itr)
     sorted.emplace(itr->first, make_pair(itr->second.m_Date.m_Time, itr->second.m_Cnt));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming that you have m_Items as

struct Date {
    std::size_t m_Time;
};

struct MyStruct
{
    Date m_Date;
    std::size_t m_Cnt;
};

std::multimap<std::string, MyStruct> m_Items;

then you need to

for (auto itr = m_Items.begin(); itr != m_Items.end(); ++itr)
sorted.emplace(itr->first, std::map<size_t, size_t>{ {itr->second.m_Date.m_Time, itr->second.m_Cnt} });
//                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Your map’s value is again a map (i.e. std::map<size_t, size_t>) not a std::par. Therefore, you need to insert as above.


In with the help of structured binding declaration, and with a range based for loop(since ), you could write much intuitive:

for (const auto& [key, value] : m_Items)
  sorted.emplace(key, std::map<size_t, size_t>{ {value.m_Date.m_Time, value.m_Cnt} });
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

Here is a (short demo.)


However, if you only need an unsorted key-value as pair as entry in sorted, I would suggest a

std::multimap<std::string, std::pair<size_t, size_t>> sorted;
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^

instead there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading