C++模拟实现foreach与findif

forecho里面设计到了仿函数


#include<vector>
#include<algorithm>
template <typename T1>
class Czs {
public :
	//仿函数不用创建对象 Czs<xxx>()就能调用函数
	void operator()(const T1& no) {
		cout << "no= " << no << " 我是你爸爸" << endl;

	}
};

template<typename T1>
void wpcshow(const T1& no) {
	std::cout << "no= " << no << " 我是你爸爸" << std::endl;
}

template<typename T1,typename T2>
//                                         t2接收函数地址来回调函数
void foreach(const T1 first, const T1 last, T2 func) {
	for (auto it = first; it != last; ++it) {
		func(*it);
	}
}

int main() {
	std::vector<int> bh = { 1,2,3,4,5,6,7,8 };
	foreach(bh.begin(), bh.end(), wpcshow<int>);
	//                             如果是模板的话就要告诉被调用的函数参数类型是啥<int>
	foreach(bh.begin(), bh.end(), Czs<int>());

	return 0;
}

findif里面设计到了仿函数

template <typename T1>
class Czs {
	T1 m_no;
public:
	//添加一个构造器,调用仿函数的时候会创建对象就会调用构造器
	Czs(const T1& no):m_no(no) {
		cout << "调用了构造器Czs(const T1& no)m_no(no): m_no= " << m_no << endl;
	}

	//仿函数不用创建对象 Czs<xxx>()就能调用函数
	bool operator()(const T1& no) {
		//张三只喜欢3号
		if (no == m_no) {
			cout << "找到了no= " << no << " 我是你爸爸" << endl;
			return true;
		}
		return false;
	}
};
//
template<typename T1>
bool wpcshow(const T1& no) {
	//张三只喜欢3号
	if (no == 3) {
		cout << "找到了no= " << no << " 我是你爸爸" << endl;
		return true;
	}
	//cout << "no= " << no << " 我是你爸爸" << endl;

	return false;
}

template<typename T1, typename T2>
//                                         t2接收函数地址来回调函数
T1 findif(const T1 first, const T1 last, T2 func) {
	for (auto it = first; it != last; ++it) {
		//如果找到了那个参数就返回
		if(func(*it)==true)return it;
	}
	//没找到就返回last迭代器
	return last;
}

int main() {
	std::vector<int> bh = { 1,2,3,4,5,6,7,8 };
	
	auto it=findif(bh.begin(), bh.end(), wpcshow<int>);
	
	if (it == bh.end())cout << "查找失败" << endl;
	else cout << "查找成功" << " it= "<<*it << endl;
	//                              给有参构造器器赋值
auto it1=findif(bh.begin(), bh.end(), Czs<int>(8));

	if (it1 == bh.end())cout << "查找失败" << endl;
	else cout << "查找成功" << " it1= " << *it1 << endl;
	return 0;
}

里面涉及到了,如果查询某个数字,怎么办,这就体现了仿函数的用处,可以在类中定义一个遍历,在传参的多传这个参数就可以特定查询某个数字了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值