Vektor von Vektoren eine schöne und elegante Lösung für Ihr Problem. Hier ist eine vorgeschlagene Lösung für Ihr 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;
}
Die Lösung ist flexibel in dem Sinne, dass Sie die Anzahl der Zeilen und Spalten auswählen können. Das Ergebnis ist
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]=
Warum brauchen Sie das? – gsamaras
Was hast du probiert? Was ist deine Quelle? – NathanOliver
Welche Forschung haben Sie gemacht? – Eddge