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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With