20240512,函数对象,常用算法:遍历,查找

函数对象

函数对象基本使用

重载 函数调用操作符 的类,其对象被称为函数对象;函数对象使用重载的()时,行为类似函数调用,也叫仿函数
函数对象(仿函数)本质是一个类,不是一个函数

特点:使用时可以像普通函数那样调用,可以有参数,返回值
函数对象超出普通函数的概念,可以有自己的状态
函数对象可以作为参数传递

#include<iostream>
#include<string>
using namespace std;
class MYADD {
public:
	int operator()(int v1,int v2) {  //重载 函数调用操作符() 的类,其对象被称为函数对象;
		return v1 + v2;
	}
};
class MYprint {
public:
	MYprint() {
		this->count = 0;
	}
	void operator()(string sts) {
		cout << sts << endl;
		this->count++;
	}
	int count;//内部自己的状态
};
void doprint(MYprint& mm, string tt1) {
	mm(tt1);
}
void test01() {
	MYADD my;
	cout << my(2, 4) << endl;
	MYprint mp;
	mp("uihihii");
	mp("uihihii");
	mp("uihihii");
	mp("uihihii");
	mp("uihihii");
	cout << "myptint调用次数:\t" << mp.count << endl;

	//函数对象可以作为参数传递
	MYprint mm;
	doprint(mm, "erfweta");
	doprint(mp, "erfweta");
}
int main() {
	test01();
	system("pause");
	return 0;
}
谓词——一元谓词

返回BOOL类型的仿函数称为谓词
operator()接受一个参数,一元谓词;两个参数,二元谓词

//find_if,定义,找有没有大于五的数字

_EXPORT_STD template <class _InIt, class _Pr>
_NODISCARD _CONSTEXPR20 _InIt find_if(_InIt _First, const _InIt _Last, _Pr _Pred) { // find first satisfying _Pred
    _Adl_verify_range(_First, _Last);
    auto _UFirst      = _Get_unwrapped(_First);
    const auto _ULast = _Get_unwrapped(_Last);
    for (; _UFirst != _ULast; ++_UFirst) {
        if (_Pred(*_UFirst)) {    //如果仿函数取出的值为真,结束循环,假则继续循环
            break;
        }
    }

    _Seek_wrapped(_First, _UFirst);
    return _First;        //返回一个迭代器
}
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class great5 {
public:
	bool operator()(int val) {
		return val > 5;
	}
};
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++) {
		v.push_back(i);
	}
	//great5()匿名的函数对象,省掉了创建对象的步骤
	vector<int>::iterator it= find_if(v.begin(), v.end(), great5());
	if (it == v.end()) {
		cout << "mei you find" << endl;
	}
	else {
		cout << "find\t" << *it<<endl;
	}
}
int main() {
	test01();
	system("pause");
	return 0;
}
谓词——二元谓词
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class great5 {
public:
	bool operator()(int val1,int val2) {
		return val1>val2;
	}
};
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++) {
		int t = rand()%300;
		v.push_back(t);
	}
	sort(v.begin(), v.end());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << "  ";
	}
	cout <<endl;
	sort(v.begin(), v.end(),great5());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << "  ";
	}
	cout << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

内建函数对象

STL内建的函数对象,头文件#include<fuctional> 

算术仿函数

四则运算,NEGATE是一元运算,其他二元运算

template <class T> T plus<T>//加
template <class T> T minus<T>//减
template <class T> T multiplies<T>//乘
template <class T> T divides<T>//除
template <class T> T modulus<T>//取yu
template <class T> T negate<T>//取反   一元

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
/*
template <class T> T plus<T>//加
template <class T> T minus<T>//减
template <class T> T multiplies<T>//乘
template <class T> T divides<T>//除
template <class T> T modulus<T>//取yu
template <class T> T negate<T>//取反——一元
*/
void test01() {
	negate<int>n;
	cout<<n(50)<<endl;
	plus<int>p;
	cout << p(34, 23) << endl;
	minus<int>m;
	cout << m(34, 23) << endl;
	multiplies<int>ml;
	cout << ml(34, 23) << endl;
	modulus<int>mo;
	cout << mo(34, 23) << endl;
	cout << mo(200, 23) << endl;
	divides<int>de;
	cout << de(34, 23) << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
关系仿函数

实现关系运算

template <class T> bool equal_to<T>//==
template <class T> bool not_equal_to<T>//!=
template <class T> bool greater<T>//>
template <class T> bool great_equal<T>//>=
template <class T> bool less <T>//<
template <class T> bool less_equal <T>//<= 

//SORT
//有参
_EXPORT_STD template <class _RanIt, class _Pr>
_CONSTEXPR20 void sort(const _RanIt _First, const _RanIt _Last, _Pr _Pred) { // order [_First, _Last)
    _Adl_verify_range(_First, _Last);
    const auto _UFirst = _Get_unwrapped(_First);
    const auto _ULast  = _Get_unwrapped(_Last);
    _Sort_unchecked(_UFirst, _ULast, _ULast - _UFirst, _Pass_fn(_Pred));
}
//默认,less<>{}
_EXPORT_STD template <class _RanIt>
_CONSTEXPR20 void sort(const _RanIt _First, const _RanIt _Last) { // order [_First, _Last)
    _STD sort(_First, _Last, less<>{});
}
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
/*
template <class T> bool equal_to<T>//==
template <class T> bool not_equal_to<T>//!=
template <class T> bool greater<T>//>
template <class T> bool great_equal<T>//>=
template <class T> bool less <T>//<
template <class T> bool less_equal <T>//<=
*/
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++) {
		int t = rand() % 300;
		v.push_back(t);
	}
	sort(v.begin(), v.end());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << "  ";
	}
	cout << endl;
	sort(v.begin(), v.end(),greater<int>());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << "  ";
	}
	cout << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
逻辑仿函数

基本用不到
template <class T> bool logical_and<T>//&&
template <class T> bool logical_or<T>//||
template <class T> bool logical_not<T>//!

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
/*
template <class T> bool logical_and<T>//&&
template <class T> bool logical_or<T>//||
template <class T> bool logical_not<T>//!

*/
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++) {
		//int p = rand() % 300-200;
		int p = rand() % 300;
		v.push_back(p%2);
	}
	sort(v.begin(), v.end());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << "  ";
	}
	cout << endl;
	vector<int>v2;
	v2.resize(v.size());//先开辟好大小
	transform(v.begin(), v.end(), v2.begin(), logical_not<int>());
	for (vector<int>::iterator it = v2.begin(); it != v2.end(); it++) {
		cout << *it << "  ";
	}
	cout << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

常用遍历算法

算法头文件主要:<algorithm>,<function>,<numeric>
<algorithm>STL头文件中最大的一个,包括比较,交换,查找,遍历操作,修改等
<function>定义了模板类,用以声明函数对象
<numeric>体积很小,只包括几个在序列上面进行简单数学运算的模板函数

FOR_EACH

for_each//遍历;       for_each(iterator beg,iterator end,_func)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
/*
for_each//遍历  ;for_each(iterator beg,iterator end,_func)
transform//遍历+搬运
*/
void print1(int val) {
	cout << val << " ";
}
class print02 {
public:
	void operator()(int val) {
		cout << val << " ";
	}
};
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++) {
		int p = rand() % 300;
		v.push_back(p);
	}
	for_each(v.begin(), v.end(), print1);//普通函数把函数名放上
	cout << "_______" << endl;
	for_each(v.begin(), v.end(), print02());//函数对象要加对象
	cout << "_______" << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
TRANSFORM

transform//遍历+搬运  ;transform ( iterator beg1 , iterator end1 , iterator beg2 , _func)(源BEG,源END,目标BEG,函数名)
提前开辟空间

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
/*
for_each//遍历  ;for_each(iterator beg,iterator end,_func)
transform//遍历+搬运  ;transform(iterator beg1,iterator end1,iterator beg2,_func)(源BEG,源END,目标BEG,函数名)
*/
void print1(int val) {
	cout << val << " ";
}
class print02 {
public:
	int operator()(int val) {
		return val*100;
	}
};
void test01() {
	vector<int>v;
	vector<int>v2;
	for (int i = 0; i < 10; i++) {
		int p = rand() % 300;
		v.push_back(p);
	}
	v2.resize(v.size());
	for_each(v2.begin(), v2.end(), print1);
	cout << "_______" << endl;
	transform(v.begin(), v.end(), v2.begin(),print02());
	for_each(v2.begin(), v2.end(), print1);
	cout << "_______" << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

常用查找算法

find //查找元素
find_if  //按条件查找元素
adjacent_find  //查找相邻重复元素
binary_search  //二分法查找
count  //统计元素个数
count_if  //按条件统计元素个数 

FIND

find //查找元素,返回POS或者END()      FIND ( BEG ,END ,VALUE )

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
class Person {
public:
	Person(string n, int a) {
		this->_name = n;
		this->_age = a;
	}
	bool operator==(const Person&p) {
		if (this->_name == p._name && this->_age == p._age) {
			return true;
		}
		else {
			return false;
		}
	}
	string _name;
	int _age;
};
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++) {
		v.push_back(i);
	}
	vector<int>::iterator it=find(v.begin(), v.end(), 5);
	if (it == v.end()) {
		cout << " no find " << endl;
	}
	else {
		cout << " find :" << *it << endl;
	}
}
void test02() {
	vector<Person>p;
	Person p0("fsdef", 23);
	Person p1("复合工艺", 28);
	Person p2("粉色", 9);
	Person p3("得分·", 45);
	Person p4("啊上网服务", 53);
	p.push_back(p0);
	p.push_back(p1);
	p.push_back(p2);
	p.push_back(p3);
	p.push_back(p4);
	vector<Person>::iterator it = find(p.begin(), p.end(), p2);
	if (it == p.end()) {//需要重载==
		cout << " no find " << endl;
	}
	else {
		cout << " find :" << it->_name << it->_age << endl;
	}
}
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/619425.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

创新案例|为何农夫山泉创新战略升级为一家零售科技公司

农夫山泉上市的消息被公之于众后&#xff0c;几乎所有人都将目光投向了这家国内家喻户晓的饮料公司&#xff0c;谁都想第一时间内窥探它的庐山真面目。 当然&#xff0c;在此之前已经有多路消息通过旁敲侧击&#xff0c;从管窥中获取了一些农夫山泉的真实数据。 去年6月&…

OCR技术在历史文献数字化中的革命性作用

随着数字化技术的不断发展&#xff0c;历史文献的数字化已成为保存和传播文化遗产的重要途径。其中&#xff0c;光学字符识别&#xff08;OCR&#xff09;技术在历史文献数字化中发挥了革命性的作用&#xff0c;为研究者提供了更广阔的研究空间&#xff0c;推动了历史学研究的发…

Golang | Leetcode Golang题解之第86题分隔链表

题目&#xff1a; 题解&#xff1a; func partition(head *ListNode, x int) *ListNode {small : &ListNode{}smallHead : smalllarge : &ListNode{}largeHead : largefor head ! nil {if head.Val < x {small.Next headsmall small.Next} else {large.Next hea…

Web安全:SQL注入之布尔盲注原理+步骤+实战操作

「作者简介」&#xff1a;2022年北京冬奥会网络安全中国代表队&#xff0c;CSDN Top100&#xff0c;就职奇安信多年&#xff0c;以实战工作为基础对安全知识体系进行总结与归纳&#xff0c;著作适用于快速入门的 《网络安全自学教程》&#xff0c;内容涵盖系统安全、信息收集等…

Pytorch基础:环境变量CUDA_VISIBLE_DEVICES

相关阅读 Pytorch基础https://blog.csdn.net/weixin_45791458/category_12457644.html?spm1001.2014.3001.5482 CUDA_VISIBLE_DEVICES这个环境变量可以影响CUDA能识别到的GPU&#xff0c;并影响它映射到的cuda设备编号。 首先我们知道使用nvidia-smi命令可以查询本机GPU的相关…

vue element checkbox的实现

实现多选非常简单: 手动添加一个el-table-column&#xff0c;设type属性为selection即可&#xff1b;默认情况下若内容过多会折行显示&#xff0c;若需要单行显示可以使用show-overflow-tooltip属性&#xff0c;它接受一个Boolean&#xff0c;为true时多余的内容会在 hover 时以…

实验过程演示【计算机网络实验】

前言 这是陈旧已久的草稿2023-05-20 11:23:54 这个是计算机网络的一个实验&#xff0c;现在也不知道这个是啥来着。 现在2024-5-12 22:33:17&#xff0c;发布到[计算机网络实验]专栏中。 实验过程演示 2023-5-18 20:17:45 1&#xff0e;搭建一个多跳网络拓扑&#xff0c;…

回炉重造java----多线程

概念 注&#xff1a; main方法其实也是一个线程。在java中所以的线程都是同时启动的&#xff0c;至于什么时候&#xff0c;哪个先执行&#xff0c;完全看谁先得到CPU的资源。在java中&#xff0c;每次程序运行至少启动2个线程。一个是main线程&#xff0c;一个是垃圾收集(gc )线…

Hikyuu高性能量化研究框架助力探索

Hikyuu Quant Framework 是一款基于C/Python的开源量化交易分析与研究工具&#xff0c;主要用于A股市场的交易策略分析与回测&#xff0c;目前不支持期货等&#xff0c;需要自行改造。 Hikyuu的目标 Hikyuu的最初目的是为了快速对A股全市场股票进行策略回测和验证&#xff0c…

[数据集][目标检测]电力场景安全帽检测数据集VOC+YOLO格式295张2类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;295 标注数量(xml文件个数)&#xff1a;295 标注数量(txt文件个数)&#xff1a;295 标注类别…

Git之revert的使用

问题场景&#xff1a; 提交代码都是以merge request的形式合并到主分支master的。 由于有一个merge request被误merge了&#xff0c;这期间又有同时merge了其它内容。 如何快速将这个被误merge的request从master上revert呢&#xff1f; 实例演示&#xff1a; 下面是最近的5…

消息中间件Kafka(PHP版本)

小编最近需要用到消息中间件&#xff0c;有需要要复习一下以前的东西&#xff0c;有需要的自取&#xff0c;强调一点&#xff0c;如果真的想了解透彻&#xff0c;一定要动手&#xff0c;脑袋会了不代表就会写了 Kafka是由Scala和Java编写。Kafka是一种高吞吐量的分布式发布订阅…

Debian Linux 下给Nginx 1.26.0 编译增加Brotli算法支持

明月发现参考【给Nginx添加谷歌Brotli压缩算法支持】一文给出的方法&#xff0c;在Debian Linux 12.5下就一直编译失败&#xff0c;主要的错误是因为文件缺失&#xff0c;在专门又安装了apt-get install libbrotli-dev的依赖库后依然会因为文件缺失无法编译完成&#xff0c;就这…

用 Python 从头开始​​编写线性回归

找到最佳拟合线的方法是使用梯度下降&#xff0c;我们将随机绘制一条线&#xff0c;计算该线的误差 计算误差 给定m和b&#xff0c;我们将计算直线的误差。Eeeor用sigma表示法表示 def compute_error_for_line_given_points(b, m, points):totalError 0for i in range(0, len…

安装conda并搭建python环境(入门教程)

文章目录 1. 什么是 conda&#xff1f;1.1 Conda 与 Anaconda 的区别1.2 Conda 与 pip 的区别 2. 下载安装3. 配置并使用 conda3.1 配置下载源3.2 环境管理3.2.1 创建&#xff08;删除&#xff09;环境3.2.2 激活&#xff08;切换&#xff09;环境3.2.2 下载&#xff08;卸载&a…

机器学习——2.损失函数loss

基本概念 损失函数也叫代价函数。损失函数就是计算预测结果和实际结果差距的函数&#xff0c;机器学习的过程就是试图将损失函数的值降到最小。 图左&#xff1a;&#xff5c;t_p - t_c&#xff5c; 图右&#xff1a;&#xff08;t_p - t_c&#xff09;**2 代码实…

[OpenGL高级光照] 阴影改善

目录 一 阴影失真 二 阴影改善 2.1 减小片段深度值 2.2 降低纹理 2.3 注意事项 三 消除Repeat的问题 3.1 让裁剪矩阵的立方体变大 ​3.2 利用采样范围重置 四 精度问题 本章节源码 点击此处 一 阴影失真 在上一篇中,实现了阴影效果之后,但是我们会发现阴影效果中地面…

47-Qt控件详解:Buttons Containers1

一 QPushButton (命令按钮) #ifndef MAINWINDOW_H #define MAINWINDOW_H#include <QMainWindow> #include <QPushButton>//引入QPushButton类对应的头文件class MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget *parent nullptr);~MainWind…

【IMX6ULL项目】IMX6ULL下Linux实现产测工具框架

电子产品量产测试与烧写工具。这是一套软件&#xff0c;用在我们的实际生产中&#xff0c; 有如下特点&#xff1a; 1.简单易用&#xff1a; 把这套软件烧写在 SD 卡上&#xff0c;插到 IMX6ULL 板子里并启动&#xff0c;它就会自动测试各个模块、烧写 EMMC 系统。 工人只要按…

40 -1 入侵检测系统(IDS)- IDS的使用及规则

xampp 官网:XAMPP Installers and Downloads for Apache Friends 一、安装 XAMPP XAMPP 简介 XAMPP是完全免费且易于安装的Apache发行版,其中包含MariaDB、PHP和Perl。XAMPP开放源码包的设置让安装和使用出奇容易。 开始安装 如果命令行下载太慢,就在浏览器中下载完再拉…