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.
  • 相关阅读:
    移植tslib库出现selected device is not a touchscreen I understand的解决方法
    2017- 韦东山视频学员成果精选(三)
    2017-韦东山视频学员成果精选(二)
    2017-韦东山视频学员成果精选(一)
    字符设备驱动另一种写法—mmap方法操作LED
    使用ubuntu16.04配置linux内核和busybox出现错误的解决方法总结
    100000个嵌入式学习者遇到的PING不通问题,我们使用这一个视频就解决了,牛!
    推荐使用集串口,SSH远程登录和FTP传输三合一工具MobaXterm
    外设位宽为8、16、32时,CPU与外设之间地址线的连接方法
    Laravel 日志配置以及设置按日期记录日志
  • 原文地址:https://www.cnblogs.com/yangyingchao/p/3442213.html
Copyright © 2011-2022 走看看