Advantages of std::for_each over for loop

后端 未结 21 740
遥遥无期
遥遥无期 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 15:50

    Aside from readability and performance, one aspect commonly overlooked is consistency. There are many ways to implement a for (or while) loop over iterators, from:

    for (C::iterator iter = c.begin(); iter != c.end(); iter++) {
        do_something(*iter);
    }
    

    to:

    C::iterator iter = c.begin();
    C::iterator end = c.end();
    while (iter != end) {
        do_something(*iter);
        ++iter;
    }
    

    with many examples in between at varying levels of efficiency and bug potential.

    Using for_each, however, enforces consistency by abstracting away the loop:

    for_each(c.begin(), c.end(), do_something);
    

    The only thing you have to worry about now is: do you implement the loop body as function, a functor, or a lambda using Boost or C++0x features? Personally, I'd rather worry about that than how to implement or read a random for/while loop.

提交回复
热议问题