Declaring a dynamic 2D vector in a class

We are trying to use a 2D vector because we want the 2D array to dynamically evolve.

We tried this: In the class declaration:

vector<vector<double> > table; 

But then the table does not stand out. When we try to access members, we get segfault.

So, we tried this:

Class declaration:

  vector<vector<double> >* table; 

Constructor:

  table = new vector<vector<double> >; 

But now we got to it before (with [] []) not working.

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 he will not be freed properly, and we got the main landfill. Also, when we tried to grow an array, we would successfully build each new row.

Example:

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

If we did not, we would get segfault

+4
source share
3 answers

You will need to resize the tables before you access the elements.

 vector<vector<double> > table; table.resize(10); for (int i = 0; i < 10; ++i) table[i].resize(20); 
+5
source

Make sure your vectors are large enough to hold your elements. If the vector t has size N , the last element that 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. 
+3
source

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

+2
source

Source: https://habr.com/ru/post/1343397/


All Articles