STL-函数对象(仿函数)、谓词、内建函数对象
文章目录
前言
本文包含函数对象概念、函数对象使用、谓词概念、 一元谓词、 二元谓词、内建函数对象意义、算术仿函数(plus()、minus()、multiplies()、divides()、modulus()、negate())、关系仿函数(equal_to()、not_equal_to()、greater()、greater_equal()、less()、less_equal())、逻辑仿函数(logical_and()、logical_or()、logical_not())。
1 函数对象
1.1 函数对象概念
概念:
(1)、重载 函数调用操作符 的类,其对象常称为 函数对象
(2)、函数对象 使用重载的()时,行为类似函数调用,也叫 仿函数
本质: 函数对象(仿函数)是一个 类,不是一个函数
1.2 函数对象使用
特点:
(1)、函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
(2)、函数对象超出普通函数的概念,函数对象可以有自己的状态
(3)、函数对象可以作为参数传递
// 函数对象(仿函数)
#include <iostream> // 包含标准输入输出流头文件
using namespace std; // 使用标准命名空间
// 1、函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
class fun_Add {
public:
int operator()(int a, int b) {
// 重载函数调用操作符(),返回两数之和
return a + b;
}
};
void test01() {
fun_Add fun_add; // 通过fun_Add类,创建一个fun_add函数对象
cout << "两数之和为:" << fun_add(10, 20) << endl;
}
// 2、函数对象可以有自己的状态;函数对象超出普通函数的概念
class fun_Print {
public:
fun_Print() {
// 无参构造函数,初始化count为0
this->count = 0;
}
void operator()(string str) {
// 重载函数调用操作符(),打印传入的参数
cout << str << endl;
count++; // 统计使用次数,每调用一次加1
}
int count; // 记录内部自己的状态;如果是普通函数,需要声明全局变量或静态变量,来记录调用次数(普通函数不是类,没有成员属性)
};
void test02() {
fun_Print fun_print; // 通过fun_Print类,创建一个fun_print函数对象
fun_print("Learning C++");
fun_print("学习使用我快乐!");
fun_print("123");
cout << "fun_print调用次数为:" << fun_print.count << endl;
}
// 3、函数对象可以作为参数传递
void do_Print(fun_Print& fp, string str) {
// 函数体,打印字符串
fp(str); // fun_Print函数fun_print对象作为一个参数,向一个do_Print函数中传递,传递&mp,传递之后,利用自身重载的函数调用操作符(),调用函数
}
void test03() {
fun_Print fun_print; // 通过fun_Print类,创建一个print函数对象
do_Print(fun_print, "Hello C++"); // 利用函数对象fun_print,以及传入打印的参数"Hello C++",间接调用仿函数fun_Print
}
int main() {
test01();
cout << endl;
test02();
cout << endl;
test03();
cout << endl;
system("pause"); // 相当于在本地 Windows 调试器中的:请按任意键继续...;暂停,方便看清楚输出结果
return 0; // 程序正常退出
}
2 谓词
2.1 谓词概念
概念:
(1)、返回 bool 类型的仿函数称为 谓词
(2)、如果 operator() 接受一个参数,那么叫做一元谓词
(3)、如果 operator() 接受两个参数,那么叫做二元谓词
2.2 一元谓词
// 仿函数:返回值类型是bool数据类型,称为谓词
// 一元谓词
#include <iostream> // 包含标准输入输出流头文件
using namespace std; // 使用标准命名空间
#include <vector>
#include <algorithm>
// 结构体中定义一元谓词,用法和类的用法很想,struct中定义的函数和变量默认为public,但class中的则是默认为private
struct Greater_5 {
bool operator()(int i) {
// 重载函数调用符()的类,且返回bool类型,接收一个参数的仿函数,为一元谓词
return i > 5;
}
};
void test() {
vector<int> v; // 创建单端数组容器v,使用时必须包含头文件vector
for (int i = 0; i < 10; i++) {
v.push_back(i); // 向单端数组容器中插入十个数
}
// 查找容器中,有没有大于5的数字
// Greater_5()匿名函数对象;正常创建一个对象,需通过类Greater_5,创建一个对象,调用对象属性或方法;不想创建对象或给对象起名,可以使用匿名函数对象
// find_if():按条件查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置;使用时需包含头文件algorithm
vector<int>::iterator it = find_if(v.begin(), v.end(), Greater_5()); // 返回值类型为迭代器
if (it == v.end()) {
// 判断返回值是否是v的end()结束迭代器,如果是,则没找到;如果不是,则找到了,返回指定位置迭代器
cout << "没找到!" << endl;
}
else {
cout << "找到: " << *it << endl; // it返回的是迭代器,迭代器本质是一个指针,使用*解引用
}
}
int main