C++模拟实现foreach与findif

forecho里面设计到了仿函数


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

	}
};

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

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

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

	return 0;
}

findif里面设计到了仿函数

template 
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()就能调用函数
	bool operator()(const T1& no) {
		//张三只喜欢3号
		if (no == m_no) {
			cout << "找到了no= " << no << " 我是你爸爸" << endl;
			return true;
		}
		return false;
	}
};
//
template
bool wpcshow(const T1& no) {
	//张三只喜欢3号
	if (no == 3) {
		cout << "找到了no= " << no << " 我是你爸爸" << endl;
		return true;
	}
	//cout << "no= " << no << " 我是你爸爸" << endl;

	return false;
}

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

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

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

你可能感兴趣的:(c++,算法,开发语言)