14. STL 函数对象

4.1 函数对象

概念:

重载函数调用操作符的类,其对象常称为函数对象

函数对象使用重载的(0时,行为类似函数调用,也叫仿函数

本质:

函数对象(仿函数)是一个类,不是一个函数

4.1.1 函数对象使用

特点:

函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值

函数对象超出普通函数的概念,函数对象可以有自己的状态

函数对象可以作为参数传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MyAdd
{
public :
int operator()(int a, int b)
{
return a + b;
}
};

class MyPrint
{
public:
MyPrint():count(0) {};
void operator()(string test)
{
cout << test << endl;
count++;
}
int count;
};
void doPrint(MyPrint& mp, string test)
{
mp(test);
}
void test01()
{
MyAdd myadd;
cout << myadd(10, 10) << endl;
MyPrint myprint;
myprint("hello");
myprint("hello");
myprint("hello");
cout << myprint.count << endl;
doPrint(myprint, "hello");

}

4.2 谓词

4.2.1 谓词

概念:

·返回boo类型的仿函数称为谓词

如果operator()接受一个参数,那么叫做一元谓词

如果operator()接受两个参数,那么叫做二元谓词

4.2.2 一元谓词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void test02()
{
vector <int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector <int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());//匿名函数对象
if (it == v.end())
{
cout << "未找到" << endl;
}
else
{
cout << "zhaodaole" << *it << endl;
}
}
int main()
{
test02();
}

4.2.3 二元谓词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyCompare
{
public:
bool operator()(int a,int b)
{
return a > b;
}
};
void test03()
{
vector <int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}

sort(v.begin(), v.end(),MyCompare());
for (vector<int>::const_iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}

4.3 内建函数对象

4.3.1 内建函数对象意义

概念:

STL内建了一些函数对象

分类:

·算术仿函数

关系仿函数

·罗辑仿函数

用法:

这些仿函数所产生的对象,用法和一般函数完全相同

使用内建函数对象,需要引入头文件#include

4.3.2 算术仿函数

img
1
2
3
4
5
6
7
8
void test04()
{
negate<int>n;
cout << n(50) << endl;// -50

modulus<int>p;
cout << p(10, 20) << endl;
}

4.3.关系仿函数

img
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void test05()
{
vector <int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for (vector<int>::const_iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;

sort(v.begin(), v.end(), greater<int>());
for (vector<int>::const_iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}

4.3.逻辑仿函数

img
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void test06()
{
vector<bool> v;
v.push_back(true);
v.push_back(false);
v.push_back(true);
v.push_back(true);
v.push_back(false);

for (vector<bool>::const_iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;

vector<bool>v2;
v2.resize(v.size());

transform(v.begin(), v.end(), v2.begin(), logical_not<bool>());
for (vector<bool>::const_iterator it = v2.begin(); it != v2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}

14. STL 函数对象
http://binbo-zappy.github.io/2024/11/27/cpp/14-STL 函数对象/
作者
Binbo
发布于
2024年11月27日
许可协议