関数内関数
そういえばC++で関数内に関数が定義できたんだった。
STLのアルゴリズムで一度しか使わないような叙述関数を定義するときに便利そう。
ただし関数オブジェクト版はCygwin上のGCC3.4.4でコンパイルエラーになった。
(VC2005では両方OK)
#include <stdio.h> #include <vector> #include <algorithm> #define USE_FUNCTOR struct Test { Test(bool InFlag):IsDeleted(InFlag){} bool IsDeleted; // 存在フラグ }; int main() { using namespace std; vector<Test> Tests; Tests.push_back(Test(false)); Tests.push_back(Test(true)); Tests.push_back(Test(false)); printf("Tests.size() = %d\n",Tests.size()); #if defined(USE_FUNCTOR) // 関数オブジェクト版 struct { bool operator()(Test& InTest) { if (InTest.IsDeleted) { return true; } return false; } } IsDeleted; #else // staticメンバー関数版 struct local{ static bool IsDeleted(Test& InTest) { if (InTest.IsDeleted) { return true; } return false; } }; #endif // 存在フラグのたっていないものを削除 #if defined(USE_FUNCTOR) vector<Test>::iterator End = remove_if(Tests.begin(), Tests.end(), IsDeleted); Tests.erase(End, Tests.end()); #else vector<Test>::iterator End = remove_if(Tests.begin(), Tests.end(), local::IsDeleted); Tests.erase(End, Tests.end()); #endif printf("Tests.size() = %d\n",Tests.size()); return 0; }