Should one prefer STL algorithms over hand-rolled loops?

后端 未结 11 1463
[愿得一人]
[愿得一人] 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:26

    It depends on:

    • Whether high-performance is required
    • The readability of the loop
    • Whether the algorithm is complex

    If the loop isn't the bottleneck, and the algorithm is simple (like for_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability. (Locality of logic is key.)

    However, now that C++0x/C++11 is supported by some major compilers, I'd say use STL algorithms because they now allow lambda expressions — and thus the locality of the logic.

提交回复
热议问题