2007年8月7日火曜日

STL(for_eachでメンバ関数を使う)

STLの勉強中に詰まったところ。

#include <algorithm> に宣言されている for_each 関数を使用してみた。
for_each とは STL の iterator を使って全ての要素に対して処理を行なう関数です。
これがなかなかの曲者でして…

使用例
----
#include <algorithm>
#include <vector>
#include <cstdio>

void Print(int x) {
printf("[%d]\n", x);
}

int main() {
vector v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for_each(v.begin(), v.end(), Print);
return 0;
}

----

これやと普通に使えるのですが、
メンバ関数を for_each で使おうと思うと…コンパイルエラー
↓これやとコンパイルエラー
----
#include <algorithm>
#include <vector>
#include <cstdio>

class hoge {
public:
hoge();
void Foo();
void Print(int x) { printf("[%d]\n", x); }
};

void hoge::Foo() {
std::vector v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::for_each(v.begin(), v.end(), &(this->Print));
}

int main() {
hoge h;
h.Foo();
return 0;
}

----

他いろいろ試してみたが…どれもダメやった。
std::for_each(v.begin(), v.end(), this->Print);
std::for_each(v.begin(), v.end(), hoge::Print);
std::for_each(v.begin(), v.end(), &(hoge::Print));

調べた結果
メンバ関数を使用するには
functional を include して
mem_fun と bind1st を使うといけるとのこと。
ソースを書き直してみたら見事コンパイル通った!
----
#include <algorithm>
#include <vector>
#include <cstdio>
#include <functional>

class hoge {
public:
hoge(){};
void Foo();
static void staticPrint(int x) { printf("[%d]\n", x); }
void Print(int x) { printf("[%d]\n", x); }
};

void hoge::Foo() {
std::vector v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::for_each(v.begin(), v.end(), std::bind1st(std::mem_fun(&hoge::Print), this));
std::for_each(v.begin(), v.end(), &hoge::staticPrint);
}

int main() {
hoge h;
h.Foo();
return 0;
}
----

こそっと static のメンバ関数も使ってみたけど
static のメンバ関数は普通に呼び出せる。

mem_fun とか bind1st を使う事を考えれば…
メンバ関数を使わない方がよさそう。

.

0 件のコメント:

ラベル