C++之内建函数对象

C++之内建函数对象

算术仿函数

复制代码
#include<iostream>
using namespace std;
#include<functional>//内建函数对象头文件
//内建函数对象 算术仿函数

void test()
{
	// negate 一元仿函数 取反仿函数
	negate<int>n;
	cout << n(100) << endl;

	//plus 二元仿函数 加法
	plus<int>p;
	cout << p(20, 30) << endl;
}

int main()
{
	test();

	system("pause");
	return 0;
}

关系仿函数

复制代码
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<functional>//内建函数对象头文件
//内建函数对象 关系仿函数
//大于greater
class MyCompare
{
public:
	bool operator()(int v1, int v2)
	{
		return v1 > v2;
	}
};
void test()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(50);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);

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

int main()
{
	test();

	system("pause");
	return 0;
}

逻辑仿函数

复制代码
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<functional>//内建函数对象头文件
//内建函数对象 逻辑仿函数
//逻辑非logical_not

void test()
{
	vector<int>v;
	v.push_back(true);
	v.push_back(false);
	v.push_back(true);
	v.push_back(false);
	v.push_back(true);

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

	//利用逻辑非 将容器v 搬运到 容器v2中, 并执行取反操作
	vector<int>v2;
	v2.resize(v.size());

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

int main()
{
	test();

	system("pause");
	return 0;
}
相关推荐
递归不收敛20 小时前
一、Java 基础入门:从 0 到 1 认识 Java(详细笔记)
java·开发语言·笔记
夜猫逐梦21 小时前
【VC】 error MSB8041: 此项目需要 MFC 库
c++·mfc
zhangfeng113321 小时前
win7 R 4.4.0和RStudio1.25的版本兼容性以及系统区域设置有关 导致Plots绘图面板被禁用,但是单独页面显示
开发语言·人工智能·r语言·生物信息
姓刘的哦1 天前
Qt中的QWebEngineView
数据库·c++·qt
C_player_0011 天前
——贪心算法——
c++·算法·贪心算法
SundayBear1 天前
QT零基础入门教程
c++·qt
子午1 天前
Python的uv包管理工具使用
开发语言·python·uv
kyle~1 天前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
奔跑吧邓邓子1 天前
【C++实战⑦】C++函数实战:从基础到项目应用
c++·实战·函数
HMBBLOVEPDX1 天前
C++(静态函数)
开发语言·c++