Nov 15, 2021 at 9:40pm Nov 15, 2021 at 9:40pm UTC
The problem with an empty 2D vector you can't simply push back a value. As you can with a 1D vector.
1. You should create a temporary vector to hold a row's data and push back that temp vector back into your vector.
OR
2. Size the 2D vector when you create it and use operator[]/.at to fill the vector with the read values.
Nov 16, 2021 at 6:12am Nov 16, 2021 at 6:12am UTC
Thanks! But is it possible to do it without using constructors and classes? I'm beginner and want to use simpliest ways
Nov 16, 2021 at 11:24am Nov 16, 2021 at 11:24am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
vector< vector<int > > fileIn( const char * filename )
{
vector< vector<int > > arr;
ifstream in( filename );
if ( in )
{
for ( string line; getline( in, line ); )
{
stringstream ss( line );
vector<int > row;
for ( int i; ss >> i; ) row.push_back( i );
arr.push_back( row );
}
}
else
{
cerr << "Boo! No such file\n" ;
}
return arr;
}
int main()
{
const char * FILE_NAME = "myfile.txt" ;
vector< vector<int > > A = fileIn( FILE_NAME );
for ( auto & row : A )
{
for ( auto e : row ) cout << e << '\t' ;
cout << '\n' ;
}
}
Last edited on Nov 16, 2021 at 11:25am Nov 16, 2021 at 11:25am UTC