Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional strings in C++

Tags:

c++

stl

matrix

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.

like image 818
dada Avatar asked Dec 03 '22 12:12

dada


2 Answers

The question seems to imply that the data structure needed is a set of n lines with m characters each. There are two ways to think of this -- as an nxm char matrix, or as n m-character vectors (and a string is similar but not identical to vector<char>).

So it seems you don't want a vector of vectors of strings, you want either a vector of vectors of chars, or just a vector of strings.

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 m and n are known beforehand) use something like push_back to add to the end.

Note also that the cin>>s reads an entire line from stdin (which makes the vector<string> solution a bit easier to deal with, I think).

like image 169
Andrew Jaffe Avatar answered Dec 25 '22 21:12

Andrew Jaffe


When inserting something new into a vector, you can't just allocate by index - you need to use the push_back method or something similar.

    for(i=0;i<n;i++) {
            vector<string> row;
            for(j=0;j<m;j++) {
                    cin>>s;
                    row.push_back(s);
            }
            table.push_back(row);
    }
like image 41
Samir Talwar Avatar answered Dec 25 '22 23:12

Samir Talwar