How can I display the content of a map on the console?

前端 未结 7 1457
轻奢々
轻奢々 2020-12-28 13:41

I have a map declared as follows:

map < string , list < string > > mapex ; list< string > li;

How can I disp

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 13:56

    If you can use C++11 features, then I think range-based for loops as proposed in The Paramagnetic Croissant's answer provide the most readable option. However, if C++17 is available to you, then you can combine those loops with structured bindings to further increase readability, because you no longer need to use the first and second members. For your specific use case, my solution would look as follows:

    std::map> mapex;
    mapex["a"] = { "1", "2", "3", "4" };
    mapex["b"] = { "5", "6", "7" };
    
    for (const auto &[k, v] : mapex) {
        std::cout << "m[" << k.c_str() << "] =";
        for (const auto &s : v)
            std::cout << " " << s.c_str();
        std::cout << std::endl;
    }
    

    Output:

    m[a] = 1 2 3 4
    m[b] = 5 6 7

    Code on Coliru

提交回复
热议问题