How can I traverse/iterate an STL map?

前端 未结 6 584
栀梦
栀梦 2021-01-30 02:14

I want to traverse an STL map. I don\'t want to use its key. I don\'t care about the ordering, I just look for a way to access all elements it contains. How can I do this?

6条回答
  •  难免孤独
    2021-01-30 02:55

    C++17

    Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. The resulting code, e.g. for printing all elements of a map, is short and well readable:

    std::map m{ {3, "a"}, {5, "b"}, {9, "c"} };
    
    for (const auto &[k, v] : m)
        std::cout << "m[" << k << "] = " << v << std::endl;
    

    Output:

    m[3] = a
    m[5] = b
    m[9] = c

    Code on Coliru

提交回复
热议问题