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