• string 转换为数值


    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

  • 相关阅读:
    流程控制之if判断
    各种运算符
    输入和输出
    垃圾回收机制(详细)
    3/5 作业
    3/4 作业
    数据类型
    变量
    Checkout 显示 URL /../../.. 不存在
    Tomcat8 访问 manager App 失败
  • 原文地址:https://www.cnblogs.com/deepllz/p/15152335.html
Copyright © 2020-2023  润新知