// あるコンテナから指定した条件を満たす要素だけを // 別のコンテナにコピーする(vector) #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> using namespace std; // predicate struct pred : std::unary_function<string, bool> { bool operator()( const string& str ) const { return str != "hogehoge" ; } }; int main() { vector<string> strVec; strVec.push_back( "foo" ); strVec.push_back( "bar" ); strVec.push_back( "hogehoge" ); strVec.push_back( "aaa" ); strVec.push_back( "bbb" ); strVec.push_back( "ccc" ); vector<string> strVec2; remove_copy_if( strVec.begin(), strVec.end(), back_inserter( strVec2 ), pred( ) ); cout << "copied vector size = " << strVec2.size() << endl; for ( int i=0; i < strVec2.size( ) ; i++ ) { cout << strVec2[i] << endl; } return 0; } /* remove_copy_if() は"条件を満たさないものをコピーする"ので、 第4引数には、狙った条件とは逆の条件を与えること。 上の例では "hogehoge" だけ抽出したいので return str != "hogehoge" ; となっていることに注目。 Predicate(述語オブジェクト)は unary_function<>から継承して作成する `関数オブジェクト'である。 remove_copy_if()が使えるコンテナは順序コンテナ(Sequence Container)だけ。 */ // end of file