Read file from txt using 2d vectors

2020-06-27 09:05发布

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];
        }
    }

}

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

标签: c++ vector
1条回答
够拽才男人
2楼-- · 2020-06-27 09:54

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

You could also set the size right at the declaration of 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];
        }
    }

}
查看更多
登录 后发表回答