可以使用基于范围的for循环轻松迭代地图的值吗? [英] Can I easily iterate over the values of a map using a range-based for loop?

查看:150
本文介绍了可以使用基于范围的for循环轻松迭代地图的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我当前的代码:

  std :: map< float,MyClass *>傻瓜

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

有没有办法这样做?

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


解决方案

href =http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html =noreferrer> Boost.Range的 map_values 适配器:

  #include< boost / range /适配器/ map.hpp> (auto&& i:foo | boost :: adapters :: map_values)

{
i-> bar();
}

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


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

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

解决方案

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

这篇关于可以使用基于范围的for循环轻松迭代地图的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆