c++ - 如何将包含 double 的 std::string 转换为 double vector ?

标签 c++ c++11

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

std::string pointLine = "1 1 1";

第二种情况是给定的参数是一个 std::string,其中包含三个我需要将其转换为 double 的“尚未 double ”:

std::string pointLine = "1.23 23.456 3.4567"

我写了下面的方法:

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;

这适用于第一种情况,但不适用于本应转换为 double 的行。

所以我尝试了解决方案 Double split in 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;

最佳答案

您可以直接从迭代器初始化 vector ,而不是复制。

// 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>()
  };
}

这对你的整数来说是完全一样的。您的 int-approach 不会像 "123 456 789"

这样的字符串执行您想要的操作

关于c++ - 如何将包含 double 的 std::string 转换为 double vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25444449/

相关文章:

c++ - 调用转换函数后是否调用了移动构造函数?

c++ - 使用 boost 解析符号链接(symbolic link)时,结果不等于原始路径名

c++ - 在释放互斥锁之前或之后通知消费者线程?

c++ - #define 跨越整个程序

c++ - 使用 std::function 对象将自定义删除器传递给 std::unique_ptr

c++ - 如何在非常量指针集合中搜索常量指针?

c++ - 为什么当我在谷歌测试程序中定义一个 const 字符串时会发生段错误?

c++ - 将预构建的 Qt 二进制文件用于 MSVS 2008 和 MSVS 2010

c++ - 我可以忽略 "Intellisense: (E0028) expression must have a constant value"吗?

c++ - 我需要在 C++ 中对齐吗?