zoukankan      html  css  js  c++  java
  • [STL] 成员函数VS算法函数

    <<C++标准程序库>>语录:

      “如果高效率是你的最高目标,你应该永远优先选用成员函数”。

    ————————————————————————————————————————

    因为,在算法中的泛型算法函数,并不知道每种容器的内部工作原理,只是四平八稳的进行一样的操作,其操作可能不是每一种容器都适应....

    拿remove函数说明.

    在list和算法中都存在remove函数,我们在成员函数有相似功能的函数要尽量使用成员函数。

     1 #include <iostream>
     2 #include <list>
     3 #include <algorithm>
     4 using namespace std;
     5 
     6 template <typename T>
     7 void PRINT_ELEMENTS (const T& coll,const char * str="")  // 泛型函数
     8 {
     9     typename T::const_iterator pos; // 老版的标准中,如果需要使用模板T中的类型,
    // 而不加typedename则会把其符号识别为一个值,但是vs2008好像不存在这个问题
    10 cout << str; 11 for(pos = coll.begin();pos != coll.end();++pos) 12 cout << *pos << ' '; 13 cout << endl; 14 } 15 int main() 16 { 17 list<int> li; 18 for(int i=1;i<=6;++i) 19 { 20 li.push_back(i); 21 li.push_front(i); 22 } 23 24 copy(li.begin(),li.end(),ostream_iterator<int>(cout," ")); 25 cout<<endl; 26 27 li.remove(3); // 调用成员数,而不是调用算法中的remove。 28 29 copy(li.begin(),li.end(),ostream_iterator<int>(cout," ")); 30 cout<<endl; 31 32 PRINT_ELEMENTS(li,"all elements: "); 33 return 0; 34 }

    输出:

    6 5 4 3 2 1 1 2 3 4 5 6
    6 5 4 2 1 1 2 4 5 6   // (删除了所有的元素3)
    all elements: 6 5 4 2 1 1 2 4 5 6
    请按任意键继续. . .

    如果把成员函数换成算法函数,那么输出:

    6 5 4 3 2 1 1 2 3 4 5 6
    6 5 4 2 1 1 2 4 5 6 5 6 // (出错)
    all elements: 6 5 4 2 1 1 2 4 5 6 5 6
    请按任意键继续. . .

  • 相关阅读:
    嵌入式交叉编译环境的搭建
    linux驱动模块编写规范以及Makefiel文件的编写规范
    socket通信
    傀儡进程脱壳三步曲
    Thymeleaf 学习笔记-实例demo(中文教程)
    IntelliJ IDEA 快捷键
    github团队协作教程
    thymeleaf 学习笔记-基础篇(中文教程)
    二维码的生成
    .Net Core Web Api实践(四)填坑连接Redis时Timeout performing EVAL
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/2451282.html
Copyright © 2011-2022 走看看