C++機能モジュール実現

1860 ワード

本稿では,実用的で一般的な機能モジュールをC++で簡潔に実現するためのシリーズを作成する.
1.既知の所定の分割子でstringを分割する
機能説明:(私のアプリケーションを例に)
  • ある時点でレーザレーダセンサ走査により1080個のint型距離データが得られ、ある.txtファイルに書き込まれ、;を2つのデータ間の分割子とした.【注】1080個のデータは同じ行にある.
  • 現在、ifstreamを使用してファイルから読み込まれたローデータは、string型変数lineに保存されています.この1080個のデータをvector型変数dataに格納することを目標としています.

  • コードをつけて!バージョン1、stringストリームで実現
    std::vector split(const std::string& line) {
    	vector data;
    	istringstream record(line);     //     string ,        line 
    	int distance; char delim;        //            ,     ,  、     !
    	if (record >> distance) {
    		data.push_back(distance);
    		while (record >> delim >> distance) {
    			res.push_back(distance);
    		}
    	}
    	return data;
    }
    

    バージョン2、C言語string.hライブラリのstrtok_sを利用
    #include //         !
    
    std::vector<:int> c_split(const std::string& line, const std::string& delim) {
    	vector data;
    	if (str == "") return data;
    	char* strs = new char[line.length() + 1];
    	strcpy_s(strs, line.length() + 1, line.c_str());  // cstring     line->strs
    	char* d = new char[delim.length() + 1];
    	strcpy_s(d, delim.length() + 1, delim.c_str());  // string c        
    
    	char* token = NULL;
    	char* next_token = NULL;
    	token = strtok_s(strs, d, &next_token); //     
    	while (token) {
    		string s = token;
    		data.push_back(std::stoi(s));   //  ,         
    		token = strtok_s(NULL, d, &next_token);
    	}
    	delete[] strs;
    	delete[] d;
    	return data;
    }
    

    評価、バージョン1は本応用においてより簡潔である!ただし、バージョン2は他のアプリケーションでより優れています.例えば、;間隔の人名LiLei;HanMeimei;ZhangShengを分割することが要求される場合、バージョン1は、簡潔に実現する方法がまだ考えられていない.