STL_iterator迭代器(3)——函数和函数对象

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

一、函数和断言

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

 1 //for_each,find_if 
 2 #include <iostream>
 3 #include <cstdlib>      // Need rand(), srand()
 4 #include <ctime>        // Need time()
 5 #include <vector>       // Need vector
 6 #include <algorithm>    // Need for_each()
 7 #define VSIZE 24        // Size of vector
 8 using namespace std;
 9 
10 vector<long> v(VSIZE);  // Vector object
11  
12 // Function prototypes
13 void initialize(long &ri);
14 void show(const long &ri);
15 bool isMinus(const long &ri);  // Predicate function
16  
17 int main()
18 {
19       srand( time(NULL) );      // Seed random generator
20       
21      //for_each遍历容器,initialize函数负责初始化容器中的元素 
22       for_each(v.begin(), v.end(), initialize);
23     
24       cout << "Vector of signed long integers" << endl;
25       //for_each遍历容器,show函数负责按顺序输出 
26       for_each(v.begin(), v.end(), show);
27     cout << endl;
28  
29       // Use predicate function to count negative values
30       //    使用判定函数对负数个数进行计数
31       
32       int count = 0;
33       vector<long>::iterator p;
34       p = for_each(v.begin(), v.end(), isMinus);//调用断言函数
35       while (p != v.end()) 
36     {
37         count++;
38         p = find_if(p + 1, v.end(), isMinus);
39       }
40       cout << "Number of values: " << VSIZE << endl;
41       cout << "Negative values : " << count << endl;
42  
43       return 0;
44 }
45  
46 // Set ri to a signed integer value
47 void initialize(long &ri)    //用随机数初始化容器 
48 {
49       ri = ( rand() - (RAND_MAX / 2) );
50       //  ri = random();
51 }
52  
53 // Display value of ri
54 void show(const long &ri)    //输出 
55 {
56       cout << ri << "  ";
57 }
58  
59 // Returns true if ri is less than 0
60 bool isMinus(const long &ri)    //负数判断 
61 {
62       return (ri < 0);
63 }

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

二、函数对象

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

1 TAnyClass object;    // Construct object
2 object();                 // Calls TAnyClass::operator()() function
3 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+(),也可以是类对象。

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

注意使用了函数对象的accumulate()的用法。

accumulate() 在内部将每个容器中的对象和第三个参数作为multiplies函数对象的参数,multiplies(1,v)计算乘积。

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

三、发生器函数对象

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

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

 1 //randfunc.cpp
 2 #include <iostream>
 3 #include <cstdlib>     // Need rand(), srand()
 4 #include <ctime>       // Need time()
 5 #include <algorithm>   // Need random_shuffle()
 6 #include <vector>      // Need vector
 7 #include <functional>  // Need ptr_fun()
 8 #include <iterator>
 9 using namespace std;
10  
11 // Data to randomize
12 int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
13 vector<int> v(iarray, iarray + 10);        //以iarray数组中的元素初始化vector 
14  
15 // Function prototypes
16 void Display(vector<int>& vr, const char *s);
17 unsigned int RandInt(const unsigned int n);
18  
19 int main()
20 {
21     srand( time(NULL) );  // Seed random generator
22       Display(v, "Before shuffle:");
23  
24       pointer_to_unary_function<unsigned int, unsigned int>ptr_RandInt = ptr_fun(RandInt);  // Pointer to RandInt()//注意这行
25       random_shuffle(v.begin(), v.end(), ptr_RandInt);
26       Display(v, "After shuffle:");
27       return 0;
28 }
29  
30 // Display contents of vector vr
31 void Display(vector<int>& vr, const char *s)
32 {
33       cout << endl << s << endl;
34       copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));
35       cout << endl;
36 }
37  
38  
39 // Return next random value in sequence modulo n
40 unsigned int RandInt(const unsigned int n)
41 {
42       return rand() % n;
43 }

首先用下面的语句申明一个对象:

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()函数。

四、发生器函数类对象

下面的例子说明发生器函数类对象的使用。

 1 //fiborand.cpp
 2 #include <iostream>
 3 #include <algorithm>   // Need random_shuffle()
 4 #include <vector>      // Need vector
 5 #include <functional>  // Need unary_function
 6 #include <iterator>
 7 using namespace std;
 8  
 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 prototype
14 void Display(vector<int>& vr, const char *s);
15  
16 // The FiboRand template function-object class
17 template <class Arg>
18 class FiboRand : public unary_function<Arg, Arg> 
19 {
20       int i, j;
21       Arg sequence[18];
22       
23     public:
24       FiboRand();
25       Arg operator()(const Arg& arg);
26 };
27  
28 int main()
29 {
30       FiboRand<int> fibogen;  // Construct generator object
31       
32       cout << "Fibonacci random number generator" << endl;
33       cout << "using random_shuffle and a function object" << endl;
34       
35       Display(v, "Before shuffle:");
36       random_shuffle(v.begin(), v.end(), fibogen);
37       Display(v, "After shuffle:");
38 }
39  
40 // Display contents of vector vr
41 void Display(vector<int>& vr, const char *s)
42 {
43     cout << endl << s << endl;
44       copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));
45       cout << endl;
46 }
47  
48 // FiboRand class constructor
49 template<class Arg>
50 FiboRand<Arg>::FiboRand()
51 {
52       sequence[17] = 1;
53       sequence[16] = 2;
54       for(int n = 15; n > 0; n--)
55       {
56         sequence[n] = sequence[n + 1] + sequence[n + 2];
57      }
58       i = 17;
59       j = 5;
60 }
61  
62 // FiboRand class function operator
63 template<class Arg>
64 Arg FiboRand<Arg>::operator()(const Arg& arg)
65 {
66       Arg k = sequence[i] + sequence[j];
67       sequence[i] = k;
68       i--;
69       j--;
70       if (i == 0) i = 17;
71       if (j == 0) j = 17;
72       return k % arg;
73 }

该程序用完全不通的方法使用使用rand_shuffle。Fibonacci 发生器封装在一个类中,该类能从先前的“使用”中记忆运行结果。在本例中,类FiboRand 维护了一个数组和两个索引变量I和j。

FiboRand类继承自unary_function() 模板:

template <class Arg>

class FiboRand : public unary_function<Arg, Arg> {...

Arg是用户自定义数据类型。该类还定以了两个成员函数,一个是构造函数,另一个是operator()()函数,该操作符允许random_shuffle()算法象一个函数一样“调用”一个FiboRand对象。

五、绑定器函数对象

一个绑定器使用另一个函数对象f()和参数值V创建一个函数对象。被绑定函数对象必须为双目函数,也就是说有两个参数,A和B。STL 中的帮定器有:

  • bind1st() 创建一个函数对象,该函数对象将值V作为第一个参数A。
  • bind2nd()创建一个函数对象,该函数对象将值V作为第二个参数B。

举例如下:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <functional>
 4 #include <list>
 5 using namespace std;
 6  
 7 // Data
 8 int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 9 list<int> aList(iarray, iarray + 10);
10  
11 int main()
12 {
13       int k = 0;
14       k = count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8));
15       
16       cout << "Number elements < 8 == " << k << endl;
17       
18     return 0;
19 }

Algorithm count_if()计算满足特定条件的元素的数目。 这是通过将一个函数对象和一个参数捆绑到为一个对象,并将该对象作为算法的第三个参数实现的。 注意这个表达式:

bind1st(greater<int>(), 8)

该表达式将greater<int>()和一个参数值8捆绑为一个函数对象。由于使用了bind1st(),所以该函数相当于计算下述表达式:

8 > q

表达式中的q是容器中的对象。因此,完整的表达式

count_if(aList.begin(), aList.end(),

bind1st(greater<int>(), 8), k);

计算所有小于或等于8的对象的数目。

六、否定函数对象

所谓否定(negator)函数对象,就是它从另一个函数对象创建而来,如果原先的函数返回真,则否定函数对象返回假。有两个否定函数对象:not1()和not2()。not1()接受单目函数对象,not2()接受双目函数对象。否定函数对象通常和帮定器一起使用。例如,上节中用bind1nd来搜索q<=8的值:

count_if(aList.begin(), aList.end(),

bind1st(greater<int>(), 8), k);

如果要搜索q>8的对象,则用bind2st。而现在可以这样写:

start = find_if(aList.begin(), aList.end(), not1(bind1nd(greater<int>(), 6)));

你必须使用not1,因为bind1nd返回单目函数。

——现在的努力是为了小时候吹过的牛B!!
原文地址:https://www.cnblogs.com/pingge/p/3251045.html