Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ;
}
like image 601
Blacklight Shining Avatar asked Oct 26 '12 12:10

Blacklight Shining


People also ask

Can we use for loop in map?

for loop can be with no content, no such concept exist in map() function.

Can I update map while iterating Java?

It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java. util. ConcurrentModificationException since the remove() method of the Map interface is called during iteration.


3 Answers

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;
}
like image 79
Daniel Langr Avatar answered Oct 12 '22 06:10

Daniel Langr


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

like image 31
lovaya Avatar answered Oct 12 '22 05:10

lovaya


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

like image 21
Xeo Avatar answered Oct 12 '22 07:10

Xeo