Should one prefer STL algorithms over hand-rolled loops?

后端 未结 11 1435
[愿得一人]
[愿得一人] 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条回答
  •  Happy的楠姐
    2020-12-30 22:19

    IMO, a lot of standard library algorithms like std::for_each should be avoided - mainly for the lack-of-lambda issues mentioned by others, but also because there's such a thing as inappropriate hiding of details.

    Of course hiding details away in functions and classes is all part of abstraction, and in general a library abstraction is better than reinventing the wheel. But a key skill with abstraction is knowing when to do it - and when not to do it. Excessive abstraction can damage readability, maintainability etc. Good judgement comes with experience, not from inflexible rules - though you must learn the rules before you learn to break them, of course.

    OTOH, it's worth considering the fact that a lot of programmers have been using C++ (and before that, C, Pascal etc) for a long time. Old habits die hard, and there is this thing called cognitive dissonance which often leads to excuses and rationalisations. Don't jump to conclusions, though - it's at least as likely that the standards guys are guilty of post-decisional dissonance.

提交回复
热议问题