开发者

Declaring Dynamic 2D Vector in class

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 {
    publi开发者_开发技巧c:
    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


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);


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.


If you have Boost installed try using Boost Multi-array.


You can access the element in [][] manner by derefrencing.

Vector<vector<double>> *table ;
table = new vector<vector<double>> ( n, vector<double>( m, 0.0)) ;
cout << (*table)[i][j] ;

Most of the times, this works perfectly well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜