[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
请按任意键继续. . .

原文地址:https://www.cnblogs.com/xuxu8511/p/2451282.html