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