벡터 문제에 대한 좋은 우아한 솔루션입니다. 여기에 당신의 문제에 대한 제안 된 해결책이 있습니다.
#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;
}
해결 방법은 사용자가 행과 열의 수를 선택할 수 있다는 점에서 유연합니다. 결과는
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]=
왜 필요합니까? – gsamaras
무엇을 시도 했습니까? 당신의 근원은 무엇입니까? – NathanOliver
어떤 연구를 수행 했습니까? – Eddge