4

As in the subject how create new 2D array in C++? This code below does not work quite well.

int** t = new *int[3];
for(int i = 0; i < 3; i++)
       t[i] = new int[5];
3
  • That's really close, but RAII is preferred.
    – chris
    Commented Feb 1, 2013 at 18:27
  • What do mean with "does not work quite well"? And why not use std::vector inside another std::vector? Commented Feb 1, 2013 at 18:28
  • this question has been asked so many times. use vector... blah blah. i wish so would automatically detect potential duplicates and asks for confirmation (if there are potential dups) before every question.
    – thang
    Commented Feb 1, 2013 at 18:29

3 Answers 3

7

You have a * in the wrong spot. Try:

int **t = new int *[3];
2
  • 1
    +1 and I wish I could up-vote it again for fixing the problem rather than reinventing the wheel.
    – WhozCraig
    Commented Feb 1, 2013 at 18:31
  • In production quality C++ code, I'd use a robust RAII container like std::vector instead of raw C-like arrays allocated with new[], unless there is a strong reason to do otherwise.
    – Mr.C64
    Commented Feb 1, 2013 at 18:51
3

Would vector< vector< int > > work?

2
  • Java would work even better but unfortunatelly can't use it ; )
    – Yoda
    Commented Feb 1, 2013 at 18:36
  • 2
    Just curious why can't you use vector from std? It's a part of any C++ version.
    – dileping
    Commented Feb 1, 2013 at 19:27
0

You may want to "flatten" the 2D matrix into a 1D array, storing its elements in a convenient container like std::vector (this is more efficient than having a vector<vector<T>>). Then you can map the 2D (row, column) matrix index into the 1D array index.

If you store the elements in the matrix row-wise, you can use a formula like this:

1D array index = column + row * columns count

You can wrap that in a convenient C++ class (overloading operator() for proper matrix element access):

template <typename T>
class Matrix {
public: 
    Matrix(size_t rows, size_t columns)
        : m_data(rows * columns), m_rows(rows), m_columns(columns) {}

    size_t Rows() const { return m_rows; }

    size_t Columns() const { return m_columns; }

    const T & operator()(size_t row, size_t column) const { 
        return m_data[VectorIndex(row, column)];
    }

    T & operator()(size_t row, size_t column) {
        return m_data[VectorIndex(row, column)];
    }

private:
    vector<T> m_data;
    size_t m_rows;    
    size_t m_columns; 

    size_t VectorIndex(size_t row, size_t column) const {
        if (row >= m_rows)
            throw out_of_range("Matrix<T> - Row index out of bound.");
        if (column >= m_columns)
            throw out_of_range("Matrix<T> - Column index out of bound.");           
        return column + row*m_columns;
    }
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.