Declaring Dynamic 2D Vector in class

前端 未结 4 508
[愿得一人]
[愿得一人] 2021-01-03 05:44

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

        
相关标签:
4条回答
  • 2021-01-03 06:30

    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 讨论(0)
  • 2021-01-03 06:31

    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.
    
    0 讨论(0)
  • 2021-01-03 06:37

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

    0 讨论(0)
  • 2021-01-03 06:46

    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);
    
    0 讨论(0)
提交回复
热议问题