[cppll:0560] <tips> mem_fun って便利ですね
- Subject:
- [cppll:0560] <tips> mem_fun って便利ですね
- From:
- TAKATSUTO Atsushi <takatuto@...>
- Date:
- Fri, 18 Jan 2002 11:10:36 +0900
- X-Mailer:
- EdMax Ver2.91
- Message-Id:
- <20020118111036.OR7?q‐at‐nfc.co.jp>
高津戸です。
普通、mem_fun はコンテナに格納されているオブジェクトのメンバ
関数を呼び出すのに使います。
class Item
{
public:
int val;
Item(int x) : val(x){}
bool comp(int n)
{ return val == n; }
};
using namespace std;
vector<Item> cntr;
cntr.push_back(Item(1));
cntr.push_back(Item(2));
cntr.push_back(Item(3));
cntr.push_back(Item(4));
vector<Item>::iterator it = find_if(cntr.begin(), cntr.end(),
bind2nd(mem_fun1_ref(&Item::comp), 2));
しかし、比較関数にコンテナ内のオブジェクトのメンバ関数ではなく、
他のオブジェクトのメンバ関数を呼びだし、引数にコンテナ内のオブ
ジェクトを渡してもらいたい場合があります。
例えば、以下のようなクラスの comp() を比較関数としたい場合、
using namespace std;
class Comp : public vector<int>
{
public:
bool comp(int i)
{ return find(begin(), end(), i) != end(); }
};
vector<int> cntr;
cntr.push_back(1);
cntr.push_back(2);
cntr.push_back(3);
cntr.push_back(4);
Comp comp;
comp.push_back(5);
comp.push_back(3);
vector<int>::iterator it = find_if(cntr.begin(), cntr.end(),
bind1st(mem_fun1_ref(&Comp::comp), comp));
// または、
// vector<int>::iterator it = find_if(cntr.begin(), cntr.end(),
// bind1st(mem_fun1(&Comp::comp), &comp));
でだけでOK。
# <faq>の方がよかったですか?
ポインタコンテナなら、[cppll:0452]の ptr_arg_fun もつかえるはず
---
TAKATSUTO Atsushi ( takatuto@... )
普通、mem_fun はコンテナに格納されているオブジェクトのメンバ
関数を呼び出すのに使います。
class Item
{
public:
int val;
Item(int x) : val(x){}
bool comp(int n)
{ return val == n; }
};
using namespace std;
vector<Item> cntr;
cntr.push_back(Item(1));
cntr.push_back(Item(2));
cntr.push_back(Item(3));
cntr.push_back(Item(4));
vector<Item>::iterator it = find_if(cntr.begin(), cntr.end(),
bind2nd(mem_fun1_ref(&Item::comp), 2));
しかし、比較関数にコンテナ内のオブジェクトのメンバ関数ではなく、
他のオブジェクトのメンバ関数を呼びだし、引数にコンテナ内のオブ
ジェクトを渡してもらいたい場合があります。
例えば、以下のようなクラスの comp() を比較関数としたい場合、
using namespace std;
class Comp : public vector<int>
{
public:
bool comp(int i)
{ return find(begin(), end(), i) != end(); }
};
vector<int> cntr;
cntr.push_back(1);
cntr.push_back(2);
cntr.push_back(3);
cntr.push_back(4);
Comp comp;
comp.push_back(5);
comp.push_back(3);
vector<int>::iterator it = find_if(cntr.begin(), cntr.end(),
bind1st(mem_fun1_ref(&Comp::comp), comp));
// または、
// vector<int>::iterator it = find_if(cntr.begin(), cntr.end(),
// bind1st(mem_fun1(&Comp::comp), &comp));
でだけでOK。
# <faq>の方がよかったですか?
ポインタコンテナなら、[cppll:0452]の ptr_arg_fun もつかえるはず
---
TAKATSUTO Atsushi ( takatuto@... )