首先为什么要用函数适配器?
STL中的函数适配器分类:
(1)绑定适配器用法
将一个操作数绑定到给定值而将二元函数对象转换为一元函数对象。
bind2nd:将给定值绑定到二元函数对象的第二个实参;
bind1st:将给定值绑定到二元函数对象的第一个参数;
示例程序如下:
#include
#include
#include
#include
using namespace std;
int main()
{
int intArr[] = { 30,90,10,40,70,50,20,80 };
const int N = sizeof(intArr) / sizeof(int);
vectora(intArr, intArr + N);
vector::iterator p = find_if(a.begin(), a.end(), bind2nd(greater(), 40));
if (p == a.end())
cout << "no element greater than 40" << endl;
else
cout << "first element greater than 40 is:" << *p << endl;
system("pause");
return 0;
}
(2)指针函数适配器用法
对一般自定义的函数使用
#include
#include
#include
#include
using namespace std;
bool g(int x, int y)
{
return x > y;
}
int main()
{
int intArr[] = { 30,90,10,40,70,50,20,80 };
const int N = sizeof(intArr) / sizeof(int);
vector<int>a(intArr, intArr + N);
vector<int>::iterator p = find_if(a.begin(), a.end(), bind2nd(ptr_fun(g), 40));
if (p == a.end())
cout << "no element greater than 40" << endl;
else
cout << "first element greater than 40 is:" << *p << endl;
system("pause");
return 0;
}
(3)组合适配器
not1(…):生成一元函数的逻辑反
not2(…):生成二元函数的逻辑反
#include
#include
#include
#include
using namespace std;
int main()
{
int intArr[] = { 30,90,10,40,70,50,20,80 };
const int N = sizeof(intArr) / sizeof(int);
vector<int>a(intArr, intArr + N);
vector<int>::iterator p = find_if(a.begin(), a.end(), not1(bind2nd(greater<int>(), 15)));
if (p == a.end())
cout << "no element is not greater than 15" << endl;
else
cout << "first element that is not greater than 15 is:" << *p << endl;
system("pause");
return 0;
}
#include
#include
#include
#include
using namespace std;
int main()
{
int intArr[] = { 30,90,10,40,70,50,20,80 };
const int N = sizeof(intArr) / sizeof(int);
vector<int>a(intArr, intArr + N);
vector<int>::iterator p = find_if(a.begin(), a.end(), bind2nd(not2(greater<int>()), 15));
if (p == a.end())
cout << "no element is not greater than 15" << endl;
else
cout << "first element that is not greater than 15 is:" << *p << endl;
system("pause");
return 0;
}
(4)成员函数适配器用法
mem_fun(…):使成员函数作为函数对象,传入对象指针;
mem_fun_ref(…):使成员函数作为函数对象,传入对象引用;
#include
#include
#include
#include
using namespace std;
struct Car
{
int id;
Car(int id)
{
this->id = id;
}
void display()const
{
cout << "car" << id << endl;
}
};
int main()
{
vector<Car *>pcars;
vector<Car>cars;
for (int i = 0; i < 5; i++)
pcars.push_back(new Car(i));
for (int i = 5; i < 10; i++)
cars.push_back(Car(i));
cout << "elements in pcars:" << endl;
for_each(pcars.begin(), pcars.end(), mem_fun(&Car::display));
cout << endl;
cout << "elements in cars:" << endl;
for_each(cars.begin(), cars.end(), mem_fun_ref(&Car::display));
cout << endl;
for (size_t i = 0; i < pcars.size(); ++i)
delete pcars[i];
system("pause");
return 0;
}
本文是在贺利坚老师的视频课的内容的基础上做的总结,仅作为后续自我复习使用。