Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Dynamic 2D Vector in class

Tags:

c++

stl

vector

We're trying to use a 2D vector because we want a 2D array that will grow dynamically.

We tried this: In the class declaration:

    vector<vector<double> > table;

But then table doesn't seem to be allocated. We get a segfault when we try to access members.

So then we tried this:

Class Declaration:

    vector<vector<double> >* table;

Constructor:

     table = new vector<vector<double> >;

But now we the way we accessed it before (with [][]) doesn't work.

We tried a dummy class with this:

class myClass {
    public:
    myClass();
    ~myClass();
    vector<vector<double> > t;
 };

myClass::myClass() 
{
    t = vector<vector<double> > (10, vector<double>(10));
}

But it wouldn't free properly and we got core dumps. Also when we tried to grow the array, we'd have expclitly construct each new row.

Ex:

t[50] = vector<double>(5);
t[50][10] = 10;

If we didn't do it like this, we'd get a segfault

like image 296
mdogg Avatar asked Dec 12 '22 15:12

mdogg


2 Answers

You'll need to resize the tables before you access elements.

vector<vector<double> > table;
table.resize(10);
for (int i = 0; i < 10; ++i)
  table[i].resize(20);
like image 113
Erik Avatar answered Dec 29 '22 22:12

Erik


Make sure your vectors are large enough to store your elements. If a vector t has size N, the last element you can access is t[N-1].

t = vector<vector<double> > (10, vector<double>(10));
t[50] = vector<double>(5); // This is wrong! Vector size is 10, you access 50th.
t[50][10] = 10; // Wrong again! Vector size 5, you access 10th.
like image 30
Tugrul Ates Avatar answered Dec 29 '22 23:12

Tugrul Ates