I want to write something like 2d strings in C++.
I tried with :
vector< vector<string> > table;
int m,n,i,j;
string s;
cin>>n>>m;
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cin>>s;
table[i][j] = s;
}
}
cout << "\n\n\n\n";
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout<<table[i][j]<<" ";
}
cout<<"\n";
}
no compile errors, but when i enter input like:
10 20
.....#..............
.....#..............
.....#..............
.....#..............
######..............
.......###..........
.......#.#..........
.......###...#######
.............#.....#
.............#######
It gives me segmentation fault. Why ? What’s wrong ? And how it should be done so it would work correctly ? Thank you.
The question seems to imply that the data structure needed is a set of
nlines withmcharacters each. There are two ways to think of this — as annxmchar matrix, or asnm-character vectors (and a string is similar but not identical tovector<char>).So it seems you don’t want a
vectorofvectors ofstrings, you want either avectorofvectors ofchars, or just avectorofstrings.In any event, you have to allocate the appropriate amount of space before using table[i][j] or (slightly more idiomatic c++, but not necessary in this case since
mandnare known beforehand) use something likepush_backto add to the end.Note also that the
cin>>sreads an entire line fromstdin(which makes thevector<string>solution a bit easier to deal with, I think).