Should one prefer STL algorithms over hand-rolled loops?

后端 未结 11 1464
[愿得一人]
[愿得一人] 2020-12-30 21:29

I seem to be seeing more \'for\' loops over iterators in questions & answers here than I do for_each(), transform(), and the like. Scott Meyers suggests that stl algori

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 22:23

    The std::foreach is the kind of code that made me curse the STL, years ago.

    I cannot say if it's better, but I like more to have the code of my loop under the loop preamble. For me, it is a strong requirement. And the std::foreach construct won't allow me that (strangely enough, the foreach versions of Java or C# are cool, as far as I am concerned... So I guess it confirms that for me the locality of the loop body is very very important).

    So I'll use the foreach only if there is only already a readable/understandable algorithm usable with it. If not, no, I won't. But this is a matter of taste, I guess, as I should perhaps try harder to understand and learn to parse all this thing...

    Note that the people at boost apparently felt somewhat the same way, for they wrote BOOST_FOREACH:

    #include 
    #include 
    #include 
    
    int main()
    {
        std::string hello( "Hello, world!" );
    
        BOOST_FOREACH( char ch, hello )
        {
            std::cout << ch;
        }
    
        return 0;
    }
    

    See : http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html

提交回复
热议问题