如何将包含双精度的std :: string转换为双精度矢量?

Rea*_*tus 6 c++ c++11

我有两种输入情况,我想使用相同的方法.第一种情况是给定的参数是一个std :: string,包含三个数字,我需要转换为int:

std::string pointLine = "1 1 1";
Run Code Online (Sandbox Code Playgroud)

第二种情况是给定参数是一个std :: string,其中包含三个"not yet double",我需要将其转换为双精度数:

std::string pointLine = "1.23 23.456 3.4567"
Run Code Online (Sandbox Code Playgroud)

我写了以下方法:

std::vector<double> getVertexIndices(std::string pointLine) {


vector<int> vertVec;

vertVec.push_back((int) pointLine.at(0));
vertVec.push_back((int) pointLine.at(2));
vertVec.push_back((int) pointLine.at(4));

return vertVec;
Run Code Online (Sandbox Code Playgroud)

}

这适用于第一种情况,但不适用于应该转换为双精度的行.

于是,我的解决方案在C型双分裂.我知道我的分隔符是"".

这就是我现在想出来的,但是在第一次调用以下方法后程序崩溃了:

std::vector<double> getVertexIndices(std::string pointLine) { 

vector<double> vertVec;
char * result = std::strtok(const_cast<char*>(pointLine.c_str()), " "); 

while(result != NULL ) {
    double vert = atof (result);
    vertVec.push_back(vert);
    char * result = std::strtok(NULL, " ");
}
return vertVec;
Run Code Online (Sandbox Code Playgroud)

}

小智 11

您可以直接从迭代器初始化矢量,而不是复制.

// include <string>, <vector>, <iterator> and <sstream> headers
std::vector<double> getVertexIndices(std::string const& pointLine)
{
  std::istringstream iss(pointLine);

  return std::vector<double>{ 
    std::istream_iterator<double>(iss),
    std::istream_iterator<double>()
  };
}
Run Code Online (Sandbox Code Playgroud)

这与您的整数完全相同.你的int方法不会像你想要的那样用于字符串"123 456 789"


Rei*_*ica 8

用途std::istringstream:

std::vector<double> getVertexIndices(std::string pointLine)
{
  vector<double> vertVec;
  std::istringstream s(pointLine);
  double d;
  while (s >> d) {
    vertVec.push_back(d);
  }
  return vertVec;
}
Run Code Online (Sandbox Code Playgroud)

真的很简单.您构造一个将从字符串中读取的流.然后只需使用常规流提取来填充向量.

当然,您可以利用标准的库迭代器适配器和类似的东西来生成这样的东西:

std::vector<double> getVertexIndices(std::string pointLine)
{
  std::vector<double> vec;
  std::istringstream s(pointLine);
  std::copy(
    std::istream_iterator<double>(s)  // start
    , std::istream_iterator<double>()  // end
    , std::back_inserter(vec)  // destination
  );
  return vec;
}
Run Code Online (Sandbox Code Playgroud)

作为旁注(感谢@ikh),您可能希望更改函数以获取const std::string &- 不需要按值获取字符串.

  • `pointLine`是`const std :: string&`不是更好吗? (3认同)