Troubles manipulating vector in two dimendions

Hi,

I am writing a program organized in some classes divided into some files.

In file gpa.h and gpa.cpp is the declaration of class gpa. In file gpa.h I did:

static vector<vector<double> > matrix;

The above line is outside any class declaration.

There is another file/class LoadFile, this class have a method getmatrix. In fact getmatrix load a matrix inside matrix(declared in gpa.h).

The problem is that I need to setup the size of matrix, for that, before store the values in matrix I create another matrix mx and copy that one into matrix:

vector<vector<double> > mx(n_cols, vector<double>(n_lines));
matrix = mx;

Is there a more direct way to setup the size of matrix?

I do only know the size of matrix in executon time.
You can use pointers to vectors, but that sort of defeats the purpose of using a vector. Vectors are meant to be as a means to store dynamic data and it's job is to manage how that data is stored. So you should give it a size that should suit your needs and it will resize its internal array if it needs to. Since you know the size of the matrix at execution time, assuming it's not going to change often, what's stopping you from using a pointer to an array of pointers to arrays?
I can offer two solutions.

The first one involves boost and just reduces the "resize" operation to two lines of code:

1
2
3
4
5
6
7
8
9
10
#include <boost/bind.hpp>
#include <vector>

typedef std::vector< std::vector< double > > matrix_t;

void resize_matrix( matrix_t& mat, size_t rows, size_t cols ) {
    mat.resize( rows );
    std::for_each( mat.begin(), mat.end(),
       boost::bind( &matrix_t::resize, _1, cols ) );
}


The second one is a design change to use a 1D array to "simulate" a 2D array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class matrix_t {
  public:
      // For example:
     double operator()( size_t row, size_t col ) const
        { return data[ index_of( row, col ) ]; }

  private:
      typedef std::vector< double > container_t;
     
      int rows;
      int cols;
      container_t data;

  private:
     size_t index_of( size_t row, size_t col ) const
        { return row * cols + col; }
};

Topic archived. No new replies allowed.