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

后端 未结 4 1209
醉梦人生
醉梦人生 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 <map>
    #include <ranges>
    
    std::map<float, MyClass*> foo;
    
    for (auto const &i : foo | std::views::values)
        i->bar();
    

    Code on Wandbox

    0 讨论(0)
  • 2021-02-03 21:12

    The magic lies with Boost.Range's map_values adaptor:

    #include <boost/range/adaptor/map.hpp>
    
    for(auto&& i : foo | boost::adaptors::map_values){
      i->bar();
    }
    

    And it's officially called a "range-based for loop", not a "foreach loop". :)

    0 讨论(0)
  • 2021-02-03 21:13
    std::map<float, MyClass*> foo;
    
    for (const auto& any : foo) {
        MyClass *j = any.second;
        j->bar();
    }
    

    in c++11 (also known as c++0x), you can do this like in C# and Java

    0 讨论(0)
  • 2021-02-03 21:30

    From C++1z/17, you can use structured bindings:

    #include <iostream>
    #include <map>
    #include <string>
    
    int main() {
       std::map<int, std::string> m;
    
       m[1] = "first";
       m[2] = "second";
       m[3] = "third";
    
       for (const auto & [key, value] : m)
          std::cout << value << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题