Vector of vectors is a nice and elegant solution to your problem. Here is a suggested solution to your problem.
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
vector<vector<string>> strTo2DStr(const string& str, const int& r, const int& c)
{
vector<vector<string>> mat;
int rows(r), cols(c);
vector<string> words;
istringstream ss(str);
copy(istream_iterator<string>(ss),istream_iterator<string>(),back_inserter(words));
int counter(0);
for ( int i(0); i < rows; ++i ){
vector<string> temp;
for ( int j(0); j < cols; ++j){
if ( counter < words.size() )
temp.push_back(words[counter++]);
else
temp.push_back("");
}
mat.push_back(temp);
}
return mat;
}
int main ()
{
string str("Hello I am writing c++ code");
int rows(3), cols(3);
vector< vector<string> > mat = strTo2DStr(str,rows,cols);
cout << str << endl << endl;
for ( int i(0); i < rows; ++i )
for ( int j(0); j < cols; ++j)
cout << "mat[" << i << "]["<< j << "]= " << mat[i][j] << " " << endl;
return 0;
}
The solution is flexible in the sense that you can choose the number of rows and columns. The result is
Hello I am writing c++ code
mat[0][0]= Hello
mat[0][1]= I
mat[0][2]= am
mat[1][0]= writing
mat[1][1]= c++
mat[1][2]= code
mat[2][0]=
mat[2][1]=
mat[2][2]=