lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

output for nested std::map

Mon Dec 21, 2015 3:04 pm

std::map<int, std::map<std::string, std::pair<int, std::string>>>mfvs;
I want to output the std::string the first part of inner map.

for (const auto& iter :mfvs)
{
std::cout << iter.second.first << "\n";
}
this gives me an error

User avatar
AndyD
Posts: 2334
Joined: Sat Jan 21, 2012 8:13 am
Location: Melbourne, Australia
Contact: Website

Re: output for nested std::map

Tue Dec 22, 2015 12:49 am

lilzz wrote:...I want to output the std::string the first part of inner map...
Which std::string? The key to the inner std::map or the second part of the std::pair (that is the value in the inner std::map)?

You don't appear to be understanding what is happening when you iterate over the contents of a container. Your code snippet is a map of maps. For example the contents of mfvs could look like this:-

Code: Select all

{
    1 : { "jack" : { 1, "frost }, "jill" : { 2, "snow" }, "jane" : { 3, "sleet" } },
    2 : { "john" : { 1, "sun" }, "kate" : { 1, "hail" } },
    ...
}
Anyway the code would look like this:

Code: Select all

std::map<int, std::map<std::string, std::pair<int, std::string>>>mfvs;

for (const auto& iter : mfvs)
{
    // iter.second is the inner std::map ... it has no member 'first' ... you need to iterate over the inner std::map as it (potentially) holds multiple values.

    for (const auto& iter2 :  iter.second)
    {
        // to print out the std::string 'key's for the inner maps ...
        // note: how are you going to know which outer std::map these values belong to.

        std::cout << iter2.first << "\n";

        // to print out the std::string that is the second part of the std::pair (that is the 'value' in the inner std::map)

        std::cout << iter2.second.second << "\n";
    }
}

Return to “C/C++”