stl算法设计理念:函数对象和函数对象当参数和返回值

// 函数对象.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <algorithm>
#include <functional>

using namespace std;

//函数对象:类重载了运算符()
template <typename T>
class ShowElemt{
public:
	ShowElemt(){
		n = 0;
	}
	void operator()(T &t){//重载()
		n++;
		cout << t << " ";
	}
	void printN(){
		cout << "n:" << n <<" ";
	}
private:
	int n;
};

//是否整除 一元谓词
template<typename T>
class IsDiv{
public:
	IsDiv(const T &divsor){
		this->divsor = divsor;
	}
	bool operator()(T &t){
		return (t%divsor == 0);
	}
private:
	T divsor;
};

template <typename T>
void FuncShowElemt(T &t){
	cout << t << endl;
}

//普通函数
void FuncShowElemt2(int &t){
	cout << t << endl;
}
//函数对象 定义:函数对象和普通函数的区别
//函数对象是属于类对象,能突破函数的概念,能保持调用状态信息
int main01()
{
	int a = 10;
	ShowElemt<int> showElemt;
	showElemt(a);//函数对象的()执行,很像一个函数//仿函数   //10
	FuncShowElemt<int>(a);//10
	FuncShowElemt2(a);//10
	return 0;
}
//for_each算法中,函数对象当函数参数
//for_each算法那中,函数对象当返回值
int main02(){
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);
	//用这个算法遍历容器里所有元素
	for_each(v1.begin(),v1.end(),ShowElemt<int>());//匿名函数对象,匿名仿函数对象
	//用普通函数做一个回调函数
	for_each(v1.begin(),v1.end(),FuncShowElemt2);//谁使用for_each,谁去写回调函数的入口地址
	ShowElemt<int> show1;
	//函数对象做函数参数
	//for_each算法的函数对象的传递 是值传递,不是引用传递 必须要接for_each的返回值(匿名函数对象)
	show1 = for_each(v1.begin(), v1.end(), show1);
	show1.printN();// n:3    表示调用了三次   函数对象
	return 0;
}
int main(){
	vector<int> v2;
	for (int i = 10; i < 23; i++){
		v2.push_back(i);
	}
	int a = 4;
	IsDiv<int> isDiv(a);//函数对象
	vector<int>::iterator it;
	it=find_if(v2.begin(), v2.end(), isDiv);//函数对象做一元谓词
	//find_if(v2.beigin(),v2.end(0,myDiv<int>(4));
	if (it == v2.end()){
		cout << "容器中没有值是4的倍数" << endl;
	}
	else{
		cout << "第一个被4整除的元素:" << *it << endl;
	}
	//find_if返回值是一个迭代器
	
	return 0;
}



结论:分清楚stl算法返回的值时迭代器还是谓词(函数对象)是stl算法入门的重点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值