土曜日, 11月 16, 2013

C++ STL - Partition関数

STL algorithmのpartition関数は特定の要素をリスト中で仕分けできる便利な関数なので覚えておくとよいことが色々あるかも.以下の例はファイル名のリスト中jpegファイル名の要素とそうでない要素を分類する例.

#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;

static vector<string> JPEG_POSTFIX;

void init() {

 JPEG_POSTFIX.push_back(".jpg");
 JPEG_POSTFIX.push_back(".jpeg");

}

bool IsJpeg(const string& s) {
        // should use boost's to_lower, though!
 vector<string>::iterator iter;
 for(iter = JPEG_POSTFIX.begin();iter != JPEG_POSTFIX.end();iter++ ) {
  if(s.find(*iter) != string::npos)
   return true;
 }
 return false;

}

int main() {

 init();
 istringstream f("neko.jpg tako.jpeg ika.png rakko.gif fugu.jpg");
 vector<string> fileList;
 string s;
 while(getline(f,s,' ')) {
  fileList.push_back(s);
 }
 cout << "## before partitioning.." << is_partitioned( fileList.begin(),fileList.end(),IsJpeg ) << endl;
 for_each(fileList.begin(),fileList.end(),[](string& s){cout << s << " "; });
 partition(fileList.begin(),fileList.end(),IsJpeg);
 cout << endl << "## after partitioning.." << is_partitioned( fileList.begin(),fileList.end(),IsJpeg ) << endl;
 for_each(fileList.begin(),fileList.end(),[](string& s){cout << s << " "; });
 cout << endl;

 return 0;

}


0 件のコメント: