[C++]STL-関数オブジェクトアダプタ
24316 ワード
関数オブジェクトアダプタは、バインド(bind)、否定(negate)、および一般関数またはメンバー関数の修飾を含むいくつかの結合作業を完了し、関数オブジェクトにします.
bind 1 st:パラメータを関数オブジェクトの最初のパラメータにバインドする
bind 2 nd:パラメータを関数オブジェクトの2番目のパラメータにバインドする
not 1:一元関数オブジェクトを逆にする
not 2:二元関数オブジェクトを逆にする
ptr_fun:一般関数を関数オブジェクトに修飾する
mem_fun:修飾メンバー関数
mem_fun_ref:修飾メンバー関数
バインドアダプタ
逆アダプタ
メンバー関数アダプタ
bind 1 st:パラメータを関数オブジェクトの最初のパラメータにバインドする
bind 2 nd:パラメータを関数オブジェクトの2番目のパラメータにバインドする
not 1:一元関数オブジェクトを逆にする
not 2:二元関数オブジェクトを逆にする
ptr_fun:一般関数を関数オブジェクトに修飾する
mem_fun:修飾メンバー関数
mem_fun_ref:修飾メンバー関数
バインドアダプタ
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include // ,
#include
using namespace std;
//bind1st,bind2nd
//
struct MyPrint : public binary_function<int, int, void>
// , ,
// ,
{
void operator()(int v, int w) const
{
cout << "v:" << v << " val:" << w
<< " v + w:"<<v+w << endl;
}
};
void test01(){
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
MyPrint print;
int addNum = 100;
for_each(v.begin(), v.end(), bind2nd(print,addNum));
for_each(v.begin(), v.end(), bind1st(print, addNum));
//for_each ( )
// ,
//bind1st,bind2nd
//bind1st
//bind2nd
//
}
int main() {
test01();
return 0;
}
逆アダプタ
// not1,not2
struct MyCompare :public binary_function<int,int ,bool> //
{
public:
bool operator()(int v1,int v2) const{
return v1 > v2;
}
};
struct MyPrint2 {
void operator()(int v) const
{
cout << "v:" << v <<endl;
}
};
struct MyGreater : public unary_function<int, bool> // binary , unary
{
bool operator()(int val)const
{
return val < 45;
}
};
void test02() {
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(rand()%100);
}
for_each(v.begin(), v.end(), MyPrint2());
cout << "-----------" << endl;
sort(v.begin(), v.end(), MyCompare()); //
for_each(v.begin(), v.end(), MyPrint2());
cout << "-----------" << endl;
sort(v.begin(), v.end(), not2(MyCompare())); //
for_each(v.begin(), v.end(), MyPrint2());
//not1 not2
// ( ) not2, not1
vector<int>::iterator it = find_if(v.begin(), v.end(), not1(MyGreater()));
//find_if() , , not1
cout << (*it) << endl;
}
メンバー関数アダプタ
// mem_fun mem_fun_ref
class Person {
public:
Person(int age,int id):mAge(age),mId(id){}
Person(){}
void show() {
cout << " :" << this->mAge << " ID:" << this->mId << endl;
}
int mAge;
int mId;
};
void test04() {
//
// for_each ,
vector<Person> v;
Person p1(10, 20), p2(23, 59), p3(18, 44);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
for_each(v.begin(), v.end(), mem_fun_ref(&Person::show));
// : mem_fun_ref(& :: )
vector<Person*> v1;
v1.push_back(&p1);
v1.push_back(&p2);
v1.push_back(&p3);
// , mem_fun
cout << "----------------" << endl;
for_each(v1.begin(), v1.end(), mem_fun(&Person::show));
}