织梦CMS - 轻松建站从此开始!

罗索

三十分钟掌握STL(2)

jackyhwei 发布于 2010-10-29 11:43 点击:次 
三种插入迭代器如下: 普通插入器 将对象插入到容器任何对象的前面。 Front inserters 将对象插入到数据集的前面例如,链表表头。 Back inserters 将对象插入
TAG:


三种插入迭代器如下:

·        普通插入器 将对象插入到容器任何对象的前面。

·        Front inserters 将对象插入到数据集的前面——例如,链表表头。

·        Back inserters 将对象插入到集合的尾部——例如,矢量的尾部,导致矢量容器扩展。

使用插入迭代器可能导致容器中的其他对象移动位置,因而使得现存的迭代器非法。例如,将一个对象插入到矢量容器将导致其他值移动位置以腾出空间。一般来说,插入到象链表这样的结构中更为有效,因为它们不会导致其他对象移动。

Listing 5. insert.cpp

  1. #include <iostream.h> 
  2. #include <algorithm> 
  3. #include <list> 
  4.  
  5. using namespace std; 
  6.  
  7. int iArray[5] = { 1, 2, 3, 4, 5 }; 
  8.  
  9. void Display(list<int>& v, const char* s); 
  10.  
  11. int main() 
  12. list<int> iList; 
  13.  
  14. // Copy iArray backwards into iList 
  15. copy(iArray, iArray + 5, front_inserter(iList)); 
  16. Display(iList, "Before find and copy"); 
  17.  
  18. // Locate value 3 in iList 
  19. list<int>::iterator p = 
  20.     find(iList.begin(), iList.end(), 3); 
  21.  
  22. // Copy first two iArray values to iList ahead of p 
  23. copy(iArray, iArray + 2, inserter(iList, p)); 
  24. Display(iList, "After find and copy"); 
  25.  
  26. return 0; 
  27.  
  28. void Display(list<int>& a, const char* s) 
  29. cout << s << endl; 
  30. copy(a.begin(), a.end(), 
  31.     ostream_iterator<int>(cout, " ")); 
  32. cout << endl; 

运行结果如下:

$ g++ insert.cpp
$ ./a.out
Before find and copy
5 4 3 2 1
After find and copy
5 4 1 2 3 2 1
可以将front_inserter替换为back_inserter试试。

如果用find()去查找在列表中不存在的值,例如99。由于这时将p设置为past-the-end 值。最后的copy()函数将iArray的值附加到链表的后部。

混合迭代器函数
在涉及到容器和算法的操作中,还有两个迭代器函数非常有用:

·        advance() 按指定的数目增减迭代器。

·        distance() 返回到达一个迭代器所需(递增)操作的数目。

例如:

  1. list<int> iList; 
  2. list<int>::iterator p = 
  3. find(iList.begin(), iList.end(), 2); 
  4. cout << "before: p == " << *p << endl; 
  5. advance(p, 2); // same as p = p + 2; 
  6. cout << "after : p == " << *p << endl; 
  7.  
  8. int k = 0; 
  9. distance(p, iList.end(), k); 
  10. cout << "k == " << k << endl; 

advance()函数接受两个参数。第二个参数是向前推进的数目。对于前推迭代器,该值必须为正,而对于双向迭代器和随机访问迭代器,该值可以为负。

使用 distance()函数来返回到达另一个迭代器所需要的步骤。
注意

distance()函数是迭代的,也就是说,它递增第三个参数。因此,你必须初始化该参数。未初始化该参数几乎注定要失败。

函数和函数对象
STL中,函数被称为算法,也就是说它们和标准C库函数相比,它们更为通用。STL算法通过重载operator()函数实现为模板类或模板函数。这些类用于创建函数对象,对容器中的数据进行各种各样的操作。下面的几节解释如何使用函数和函数对象。

函数和断言
经常需要对容器中的数据进行用户自定义的操作。例如,你可能希望遍历一个容器中所有对象的STL算法能够回调自己的函数。例如

  1. #include <iostream.h> 
  2. #include <stdlib.h>     // Need random(), srandom() 
  3. #include <time.h>       // Need time() 
  4. #include <vector>       // Need vector 
  5. #include <algorithm>    // Need for_each() 
  6.  
  7. #define VSIZE 24        // Size of vector 
  8. vector<long> v(VSIZE); // Vector object 
  9.  
  10. // Function prototypes 
  11. void initialize(long &ri); 
  12. void show(const long &ri); 
  13. bool isMinus(const long &ri); // Predicate function 
  14.  
  15. int main() 
  16. srandom( time(NULL) ); // Seed random generator 
  17.  
  18. for_each(v.begin(), v.end(), initialize);//调用普通函数 
  19. cout << "Vector of signed long integers" << endl; 
  20. for_each(v.begin(), v.end(), show); 
  21. cout << endl; 
  22.  
  23. // Use predicate function to count negative values 
  24. // 
  25. int count = 0; 
  26. vector<long>::iterator p; 
  27. p = find_if(v.begin(), v.end(), isMinus);//调用断言函数 
  28. while (p != v.end()) { 
  29.     count++; 
  30.     p = find_if(p + 1, v.end(), isMinus); 
  31. cout << "Number of values: " << VSIZE << endl; 
  32. cout << "Negative values : " << count << endl; 
  33.  
  34. return 0; 
  35.  
  36. // Set ri to a signed integer value 
  37. void initialize(long &ri) 
  38. ri = ( random() - (RAND_MAX / 2) ); 
  39. // ri = random(); 
  40.  
  41. // Display value of ri 
  42. void show(const long &ri) 
  43. cout << ri << " "
  44.  
  45. // Returns true if ri is less than 0 
  46. bool isMinus(const long &ri) 
  47. return (ri < 0); 

所谓断言函数,就是返回bool值的函数。

函数对象
除了给STL算法传递一个回调函数,你还可能需要传递一个类对象以便执行更复杂的操作。这样的一个对象就叫做函数对象。实际上函数对象就是一个类,但它和回调函数一样可以被回调。例如,在函数对象每次被for_each()或find_if()函数调用时可以保留统计信息。函数对象是通过重载operator()()实现的。如果TanyClass定义了opeator()(),那么就可以这么使用:

TAnyClass object; // Construct object
object();          // Calls TAnyClass::operator()() function
for_each(v.begin(), v.end(), object);
STL定义了几个函数对象。由于它们是模板,所以能够用于任何类型,包括C/C++固有的数据类型,如long。有些函数对象从名字中就可以看出它的用途,如plus()和multiplies()。类似的greater()和less-equal()用于比较两个值。

注意

有些版本的ANSI C++定义了times()函数对象,而GNU C++把它命名为multiplies()。使用时必须包含头文件<functional>。

一个有用的函数对象的应用是accumulate() 算法。该函数计算容器中所有值的总和。记住这样的值不一定是简单的类型,通过重载operator+(),也可以是类对象。

Listing 8. accum.cpp

  1. #include <iostream.h> 
  2. #include <numeric>      // Need accumulate() 
  3. #include <vector>       // Need vector 
  4. #include <functional>   // Need multiplies() (or times()) 
  5.  
  6. #define MAX 10 
  7. vector<long> v(MAX);    // Vector object 
  8.  
  9. int main() 
  10. // Fill vector using conventional loop 
  11. // 
  12. for (int i = 0; i < MAX; i++) 
  13.     v[i] = i + 1; 
  14.  
  15. // Accumulate the sum of contained values 
  16. // 
  17. long sum = 
  18.     accumulate(v.begin(), v.end(), 0); 
  19. cout << "Sum of values == " << sum << endl; 
  20.  
  21. // Accumulate the product of contained values 
  22. // 
  23. long product = 
  24.     accumulate(v.begin(), v.end(), 1, multiplies<long>());//注意这行 
  25. cout << "Product of values == " << product << endl; 
  26.  
  27. return 0; 

编译输出如下:

$ g++ accum.cpp
$ ./a.out
Sum of values == 55
Product of values == 3628800
『注意使用了函数对象的accumulate()的用法。accumulate() 在内部将每个容器中的对象和第三个参数作为multiplies函数对象的参数,multiplies(1,v)计算乘积。VC中的这些模板的源代码如下:

  1. // TEMPLATE FUNCTION accumulate 
  2.  
  3. template<class _II, class _Ty> inline 
  4.  
  5.     _Ty accumulate(_II _F, _II _L, _Ty _V) 
  6.  
  7.     {for (; _F != _L; ++_F) 
  8.  
  9.         _V = _V + *_F; 
  10.  
  11.     return (_V); } 
  12.  
  13.         // TEMPLATE FUNCTION accumulate WITH BINOP 
  14.  
  15. template<class _II, class _Ty, class _Bop> inline 
  16.  
  17.     _Ty accumulate(_II _F, _II _L, _Ty _V, _Bop _B) 
  18.  
  19.     {for (; _F != _L; ++_F) 
  20.  
  21.         _V = _B(_V, *_F); 
  22.  
  23.     return (_V); } 
  24.  
  25.         // TEMPLATE STRUCT binary_function 
  26.  
  27. template<class _A1, class _A2, class _R> 
  28.  
  29.     struct binary_function { 
  30.  
  31.     typedef _A1 first_argument_type; 
  32.  
  33.     typedef _A2 second_argument_type; 
  34.  
  35.     typedef _R result_type; 
  36.  
  37.     }; 
  38.  
  39.         // TEMPLATE STRUCT multiplies 
  40.  
  41. template<class _Ty> 
  42.  
  43.     struct multiplies : binary_function<_Ty, _Ty, _Ty> { 
  44.  
  45.     _Ty operator()(const _Ty& _X, const _Ty& _Y) const 
  46.  
  47.         {return (_X * _Y); } 
  48.  
  49.     }; 

引言:如果你想深入了解STL到底是怎么实现的,最好的办法是写个简单的程序,将程序中涉及到的模板源码给copy下来,稍作整理,就能看懂了。所以没有必要去买什么《STL源码剖析》之类的书籍,那些书可能反而浪费时间。』

发生器函数对象
有一类有用的函数对象是“发生器”(generator)。这类函数有自己的内存,也就是说它能够从先前的调用中记住一个值。例如随机数发生器函数。

普通的C程序员使用静态或全局变量 “记忆”上次调用的结果。但这样做的缺点是该函数无法和它的数据相分离『还有个缺点是要用TLS才能线程安全』。显然,使用类来封装一块:“内存”更安全可靠。先看一下例子:

Listing 9. randfunc.cpp

  1. #include <iostream.h> 
  2. #include <stdlib.h>    // Need random(), srandom() 
  3. #include <time.h>      // Need time() 
  4. #include <algorithm>   // Need random_shuffle() 
  5. #include <vector>      // Need vector 
  6. #include <functional> // Need ptr_fun() 
  7.  
  8. using namespace std; 

  9. // Data to randomize 
  10. int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
  11. vector<int> v(iarray, iarray + 10); 
  12.  
  13. // Function prototypes 
  14. void Display(vector<int>& vr, const char *s); 
  15. unsigned int RandInt(const unsigned int n); 
  16.  
  17. int main() 
  18. srandom( time(NULL) ); // Seed random generator 
  19. Display(v, "Before shuffle:"); 
  20.  
  21. pointer_to_unary_function<unsigned int, unsigned int
  22.     ptr_RandInt = ptr_fun(RandInt); // Pointer to RandInt()//注意这行 
  23. random_shuffle(v.begin(), v.end(), ptr_RandInt); 
  24.  
  25. Display(v, "After shuffle:"); 
  26. return 0; 
  27.  
  28. // Display contents of vector vr 
  29. void Display(vector<int>& vr, const char *s) 
  30. cout << endl << s << endl; 
  31. copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " ")); 
  32. cout << endl; 
  33.  
  34.  
  35. // Return next random value in sequence modulo n 
  36. unsigned int RandInt(const unsigned int n) 
  37. return random() % n; 

编译运行结果如下:

$ g++ randfunc.cpp
$ ./a.out
Before shuffle:
1 2 3 4 5 6 7 8 9 10
After shuffle:
6 7 2 8 3 5 10 1 9 4
首先用下面的语句申明一个对象:

pointer_to_unary_function<unsigned int, unsigned int>
ptr_RandInt = ptr_fun(RandInt);
这儿使用STL的单目函数模板定义了一个变量ptr_RandInt,并将地址初始化到我们的函数RandInt()。单目函数接受一个参数,并返回一个值。现在random_shuffle()可以如下调用:

random_shuffle(v.begin(), v.end(), ptr_RandInt);
在本例子中,发生器只是简单的调用rand()函数。

关于常量引用的一点小麻烦(不翻译了,VC下将例子中的const去掉) (karymay)

本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201010/10375.html]
本文出处:网络 作者:karymay
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容