将字符串向量转换为双二维数组向量

时间:2016-06-23 01:48:53

标签: c++ string vector 2d-vector

vector<string>行转换为vector<vector <double> > d?

的好方法是什么?

我从文件中读取了500x9向量字符串数据,

vector<string> line;

我需要将此字符串向量转换为大小为(500行,9列)的2D向量数组

vector<vector <double> > d;

代码:

using namespace std;

int main()
{

    /// read file data ///
    std::ifstream myfile;
    myfile.open("somefile.txt");
    std::vector<string> lines;
    std::string str;
    while(getline(myfile,str))
        lines.push_back(str);
    myfile.close();

    std::vector< std::vector<double> > data;
    /// convert string to double ///
    std::transform(lines.begin(), lines.end(), data.begin(), std::stod);

}

1 个答案:

答案 0 :(得分:1)

我非常喜欢您可以找到的标准算法。但我相信你最好的情况是一个很好的旧时尚Repaint - start QGraphicsScene(0x15c7eca8) trying to draw QWidget::paintEngine: Should no longer be called QPainter::begin: Paint device returned engine == 0, type: 1 QPainter::setPen: Painter not active QPainter::viewport: Painter not active QPainter::end: Painter not active, aborted Repaint - end - 循环(如果你不确定while可以被9整除,尤其如此:Using an iterator to Divide an Array into Parts with Unequal Size

line

Live Example

请注意,对stod的调用包含在lambda中。

  • vector<vector<double>> d(line.size() / 9, vector<double>(9)); for(auto i = 0U; i + 9 <= line.size(); i += 9) { transform(next(cbegin(line), i), next(begin(line), i + 9), begin(d[i / 9]), [](const auto& it){return stod(it);}); } 无效,因为编译器不知道您是在呼叫transform(cbegin(lines), cend(lines), begin(d[i / 9]), stod)还是double stod(const string&, size_t*)
  • double stod(const wstring&, size_t*)将无效,因为函数指针
  • 未保留默认的第二个参数
  • transform(cbegin(lines), cend(lines), begin(d[i / 9]), static_cast<double (*)(const string&, size_t*)>(stod))确实与lambda
  • 等效