CPP_boost_tokenize - アールメカブ

アールメカブ


CPP_boost_tokenize

Programming

_ boost ライブラリを使って,トークン化とベクトル化

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <ctime>
using namespace std;

int main(int arg, char *argv[]){
 time_t startT, stopT;
 time(&startT);
vector<string> v;
  
 string finame;
 string ss;// strtok を使う場合は,
 // 読み込んだ行はchar 変数におさめる
 //char ss[256];
 ifstream fin;
 typedef boost::tokenizer<> tokenizer1;

 finame = argv[1];
 fin.open(finame.c_str());
 if(!fin) return 1;
  
 while(fin >> ss){
   tokenizer1 tok1( ss);
   for( tokenizer1::iterator it=tok1.begin(); it!=tok1.end(); ++it )
   //	cout << "TOKEN: " << *it << endl;
	  v.push_back(*it);
 }
 fin.close();
time(&stopT);
 cout << v.size() <<  "Time: " <<   difftime(stopT,startT) << endl;

}

以下はここからの引用

必要なヘッダ <boost/tokenizer.hpp> 出来ること 文字列切り分け リファレンス en / jp sample

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
int main()
{
	string str1 = "this   is a   pen";
	// デフォルトでは、区切り文字(空白とかコンマとか)で分割する。
	typedef boost::tokenizer<> tokenizer1;
	tokenizer1 tok1( str1 );
	for( tokenizer1::iterator it=tok1.begin(); it!=tok1.end(); ++it )
		cout << "TOKEN: " << *it << endl;
	string str2 = "20020903";
	// 4文字、2文字、2文字に分割してみる。
	const int offsets[] = {4,2,2};
	boost::offset_separator ofs( offsets, offsets+3 );
	typedef boost::tokenizer<boost::offset_separator>  
 tokenizer2;
	tokenizer2 tok2( str2, ofs );
	for( tokenizer2::iterator it=tok2.begin(); it!=tok2.end(); ++it )
		cout << "TOKEN: " << *it << endl;
	return 0;
}

実行例 TOKEN: this TOKEN: is TOKEN: a TOKEN: pen TOKEN: 2002 TOKEN: 09 TOKEN: 03

etc

まぁ、見たまんまです。コマンドラインの解析とか、 コンマ区切りテキストデータの解釈などに役立ちそう。 wchar_t型文字列の切り分けなども可能なので、 日本語環境でも使えるのではないかと。分割関数をちゃんと用意すれば、 マルチバイト文字列でもOKだと思われます。。

時間関数についてはここを参照した.

 
Link: Programming(4984d)
Last-modified: 2007-12-06 (木) 16:48:08 (5985d)