Blacklight Shining
Blacklight Shining

Reputation: 1538

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

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<float, MyClass*> foo ;

for (map<float, MyClass*>::iterator i = foo.begin() ; i != foo.end() ; i ++ ) {
    MyClass *j = i->second ;
    j->bar() ;
}

Is there a way I can do the following?

for (MyClass* i : /*magic here?*/) {
    i->bar() ;
}

Upvotes: 54

Views: 70034

Answers (4)

honk
honk

Reputation: 9743

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

Upvotes: 19

Daniel Langr
Daniel Langr

Reputation: 23497

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;
}

Upvotes: 56

lovaya
lovaya

Reputation: 465

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

Upvotes: 35

Xeo
Xeo

Reputation: 131799

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". :)

Upvotes: 25

Related Questions