Advantages of std::for_each over for loop

后端 未结 21 769
遥遥无期
遥遥无期 2020-11-29 15:23

Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some coding

21条回答
  •  余生分开走
    2020-11-29 15:52

    Personally, any time I'd need to go out of my way to use std::for_each (write special-purpose functors / complicated boost::lambdas), I find BOOST_FOREACH and C++0x's range-based for clearer:

    BOOST_FOREACH(Monster* m, monsters) {
         if (m->has_plan()) 
             m->act();
    }
    

    vs

    std::for_each(monsters.begin(), monsters.end(), 
      if_then(bind(&Monster::has_plan, _1), 
        bind(&Monster::act, _1)));
    

提交回复
热议问题