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