std::string s = "1.3,1.4,1.5"
字符串中的数字按照逗号分割,把每个数字解析出来.
void ParseStr(std::string& s, std::vector<float>& res) {
char* pos = const_cast<char*>(s.c_str());
while (1) {
float f = strtof(pos, &pos);
res.push_back(f);
if (*pos == 0) {
break;
}
++pos;
}
}
使用strtof、strtod、strtol这类api,可以避免字符串的copy. 如果使用std::stof(const std::string& str, size_t* idx = 0),就势必要做substr,这样就产生了copy,性能会有问题.
注意:stof这类api内部也是调用strtof的.
https://www.cplusplus.com/reference/cstdlib/strtod/
https://www.cplusplus.com/reference/string/stof/?kw=stof