使用2d向量从txt读取文件 [英] Read file from txt using 2d vectors

查看:117
本文介绍了使用2d向量从txt读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在2d向量的情况下,是否可以使用operator []?例如,我得到以下代码:

Is it possible to use the operator [] in case of 2d vectors? For example i got the following code:

vector<vector<string>> data;

ifstream myReadFile;
myReadFile.open("stoixeia_astheni.txt");


while (!myReadFile.eof()) {

    for(int i=0; i<1; i++){
        for (int j=0; j<4; j++){
            myReadFile  >> data[i][j];
        }
    }

}

消息超出范围。我有一个有5行和4列的文件。

I got message out of range. I have a file with 5 lines and 4 columns.

推荐答案

您的向量 data 是空的,它的 size()是0.你必须首先 resize push()

Your vector data is empty, its size() is 0. You have to resize it first or add new elements by using push_back():

while (!myReadFile.eof()) {    
    for(int i = 0; i < 1; i++){
        vector<string> tmpVec;
        string tmpString

        for (int j = 0; j < 4; j++){
            myReadFile  >> tmpString;
            tmpVec.push_back(tmpString);
        }
        data.push_bac(tmpVec);
    }
}

您也可以在声明 data

vector<vector<string>> data(5,vector<string>(4));

ifstream myReadFile;
myReadFile.open("stoixeia_astheni.txt");

while (!myReadFile.eof()) {

    for(int i=0; i < 5; i++){
        for (int j=0; j<4; j++){
            myReadFile  >> data[i][j];
        }
    }

}

这篇关于使用2d向量从txt读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆