Effective STL 43: Prefer algorithm calls to hand-written loops
tubo
posted @ 2014年9月03日 16:11
in 未分类
, 674 阅读
Suppose you have a Widget class that supports redrawing:
class Widget { public: Widget(); virtual ~Widget(); void redraw() const; };
and you'd like to redraw all the Widgets in a list, you could do it within a loop:
list<Widget> lw; // ... for (list<Widget>::iterator i = lw.begin(); i != lw.end(); ++i) { i->redraw(); }
But you could also do it with the for_each algorithm:
for_each(lw.begin(), lw.end(), mem_fun_ref(&Widget::redraw));
Why should we prefer algorithm to writing our own loop? Here are the reasons:
-
Efficiency:
Algorithms are offten more efficient than the loops programmers produce. -
Correctness:
writing loops is more suject to errors than is calling algorithms. -
maintainability:
Algorithm calls often yield code that is clear and more straightforward than the corresponding explicit loops.
(转载请注明出处,使用许可:署名-非商业性使用-相同方式共享 3.0 中国大陆许可协议 。)