In case that all rows are equally long (as it is a matrix right), I would suggest you to write a custom class Matrix
instead of working with a vector<vector<int>>
( which for sure works).
Such a class could expose an interface like:
int getWidth()
int getHeight()
int get(int x, int y)
void set(int x, int y, int value)
One can think of additional functions (like multiplication etc.) and its alot cleaner to access and to store. (Matrix m_matrix;
looks better than std::vector<std::vector<int>> m_matrix
, doesnt it?).
Internally you could use an int[][]
or an std::vector<std::vector<int>>
, depends on what you prefer, to store the actual data.
Also notice that such a class would also enforce restrictions a matrix can have, e.g like mentioned in my first sentence, equally long rows.
To actually deserialize this string, abstractly you must iterate over every line incrementing a counter and then iterate over every number incrementing another counter.
In each iteration you would then call myMatrix.set(x,y,parsedValue);
A possible implementation then might look like this:
std::string line;
int x = 0;
int y = 0;
int value;
while ( getline( std::cin, line ) ) {
std::istringstream is( line );
while(!is.eof()) {
is >> value;
myMatrix.set(x,y,value)
x++
}
y++
}
Notice that you would firstly have to initialize myMatrix
with the proper size though (atleast if you work with arrays, if your using vectors thouh you could maybe skip that)
It might be that this solution sounds alot more complicated (and yes it does take abit more time to implement), but in the end, if you want to write a easily maintainably programm and want to work with multiple Matrix
instances, this is for sure the way to go. Please notice, that this is only a suggestion, the interface can of course look different.