Can I easily iterate over the values of a map using a range-based for loop?

后端 未结 4 1213
醉梦人生
醉梦人生 2021-02-03 20:38

Is it possible to iterate over all of the values in a std::map using just a "foreach"?

This is my current code:

std::map

        
4条回答
  •  感情败类
    2021-02-03 21:10

    Since C++20 you can add the range adaptor std::views::values from the Ranges library to your range-based for loop. This way you can implement a similar solution to the one in Xeo's answer, but without using Boost:

    #include 
    #include 
    
    std::map foo;
    
    for (auto const &i : foo | std::views::values)
        i->bar();
    

    Code on Wandbox

提交回复
热议问题