zoukankan      html  css  js  c++  java
  • Effective STL 43: Prefer algorithm calls to hand-written loops

    Effective STL 43: Prefer algorithm calls to hand-written loops

    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.
  • 相关阅读:
    用Margin还是用Padding?
    更优雅的清除浮动float方法
    清除浮动float (:after方法)
    px,em,rem
    load()方法
    PHP函数详解:call_user_func()使用方法
    移动端touch事件影响click事件以及在touchmove添加preventDefault导致页面无法滚动的解决方法
    Mysql开启远程连接方法
    mysql的字符串连接符
    php使用curl访问https返回无结果的问题
  • 原文地址:https://www.cnblogs.com/yangyingchao/p/3442213.html
Copyright © 2011-2022 走看看