C++ 我可以使用基于范围的 for 循环轻松迭代地图的值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13087028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:56:25  来源:igfitidea点击:

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

c++mapfor-loopc++11

提问by Blacklight Shining

Is it possible to iterate over all of the values in a std::map using just a foreach?

是否可以仅使用 foreach 迭代 std::map 中的所有值?

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 this?

有没有办法做到这一点?

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

采纳答案by Xeo

The magic lies with Boost.Range's map_valuesadaptor:

神奇之处在于Boost.Range 的map_values适配器

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

它被正式称为“基于范围的 for 循环”,而不是“foreach 循环”。:)

回答by Daniel Langr

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

C++1z/17 开始,您可以使用结构化绑定

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

回答by lovaya

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

在 c++11(也称为 c++0x)中,你可以像在 C# 和 Java 中那样做