48

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() ;
}
4
  • 4
    Why you don't like i->second->bar() ?
    – Andriy
    Oct 26, 2012 at 12:42
  • Take a look at [this question's answer][1]. I think is exactly what you need. [1]: stackoverflow.com/questions/6963894/… Oct 26, 2012 at 12:42
  • 4
    @LyubomirVasilev: No, that one only asks how to iterate over a map in general for range-for. This one asks how to iterate specifically only over the values.
    – Xeo
    Oct 26, 2012 at 12:43
  • @Xeo Ahh, I see. I overlooked that. Oct 26, 2012 at 13:35

4 Answers 4

51

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;
}
5
  • 5
    structured bindings are awesome, but I compile with -Werror and unused-variable cries about the key not being used a lot :)
    – galois
    Feb 16, 2018 at 22:21
  • 1
    Try [[maybe_unused]] attribute. See here stackoverflow.com/q/41404001/580083 Feb 17, 2018 at 7:27
  • @galois and @ Daniel, Sorry if this is a basic question but what exactly is Structured Bindings? Thanks a lot in advance!
    – Milan
    Jun 25, 2021 at 17:06
  • @Milan Have you tried to google it? There are tons of explanations all around. Jun 26, 2021 at 4:58
  • 1
    @DanielLangr I was reading an answer and as soon as I read a new word, I just commented here. But you are right... I should have googled it first. Sorry about that. (For the future readers: I found this short & simple video on Structured Bindings quite useful: youtu.be/eUsTO5BO3WI)
    – Milan
    Jun 28, 2021 at 16:44
35
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

4
  • What do you mean by “you can do this”? Are you referring to ranged-based for loops in general? Oct 26, 2012 at 12:54
  • YES! The new C++ Standard c++11 import a new for-range syntax feature,It's easier to iterator elments in containers.for example: vector<int> vec{0, 1, 2 ,3, 4, 5, 6, 7, 8, 9};now in c++11,you can wirte code like this: for(auto any : vec) { cout << any << endl;}, you can compiler this code in visual c++ 2012, or in g++ 4.6 or higher with the argument -std=c++0x
    – lovaya
    Oct 26, 2012 at 18:15
  • 8
    Well…this is not quite helpful, as I knew about ranged-based loops before posting…my question, which @Xeo has already answered, is about how to iterate through just the values of a map, without a line like MyClass *j = any.second ; :P Oct 26, 2012 at 18:28
  • I understand auto, but why const auto&? Is it not possible to edit the variable while in loop? Mar 3, 2017 at 4:52
24

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

8
  • 1
    i would have written auto const&&. Oct 26, 2012 at 12:46
  • @Cheersandhth.-Alf I think you mean auto const &&i :) Oct 26, 2012 at 12:46
  • @Xeo /ranged-based for loop/. I knew that. I must've been looking at SO tags too long… 6_9 Anyway, thank you! This is just what I was looking for. Can you explain why the pipe there is valid? That's a bitwise or, right? Oct 26, 2012 at 12:49
  • 1
    @Blacklight: Boost.Range's adaptors overload the operator| to make chaining easier: map | map_values | filtered(pred) | transformed(blub) | reversed. :)
    – Xeo
    Oct 26, 2012 at 12:53
  • 2
    @Blacklight: It's all there in the documentation! :)
    – Xeo
    Oct 26, 2012 at 12:58
13

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

2
  • Even though I like the syntactic sugar of the "pipe" symbole here very much, the more obvious implementation would say for (auto const& it : std::views::values(foo)) it->bar(); Apr 19 at 9:09
  • 1
    I agree, with only one range adapter, the better syntax is a matter of preference. But the idea is that you can chain multiple range adapters together, and then the piping concept makes more sense.
    – honk
    Apr 19 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.