Advantages of std::for_each over for loop

后端 未结 21 705
遥遥无期
遥遥无期 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:43

    Mostly you'll have to iterate over the whole collection. Therefore I suggest you write your own for_each() variant, taking only 2 parameters. This will allow you to rewrite Terry Mahaffey's example as:

    for_each(container, [](int& i) {
        i += 10;
    });
    

    I think this is indeed more readable than a for loop. However, this requires the C++0x compiler extensions.

提交回复
热议问题