C++機能モジュール実現
本稿では,実用的で一般的な機能モジュールをC++で簡潔に実現するためのシリーズを作成する.
1.既知の所定の分割子でstringを分割する
機能説明:(私のアプリケーションを例に)ある時点でレーザレーダセンサ走査により1080個の 現在、
コードをつけて!バージョン1、
バージョン2、C言語
評価、バージョン1は本応用においてより簡潔である!ただし、バージョン2は他のアプリケーションでより優れています.例えば、
1.既知の所定の分割子でstringを分割する
機能説明:(私のアプリケーションを例に)
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は、簡潔に実現する方法がまだ考えられていない.