The literal question
” How to write the following code using new operator?
… means something else than you think it means.
The new
operator is a simple allocation function roughly directly analogous to C's malloc
, except the C++ new
operator is replacable by a user defined one.
You probably mean a new
expression. Such an expression invokes the new
operator for allocation, and then invokes a constructor for initialization, if the allocated thing is of class type. And it's type safe.
Still, for your array you'd not want that either, but simply std::vector
from the standard library.
Here's an example using a std::vector
of vectors to create a matrix:
#include <vector>
using namespace std;
auto main()
-> int
{
int const n_rows = 3;
int const n_cols = 5;
using Row = vector<int>;
vector<Row> v( n_rows, Row( n_cols ) );
// E.g. v[1] is a row, and v[1][2] is an int item in that row.
}
Even if you don't so often use matrices, it can be a good idea to wrap the general notion of a matrix, in a class. A simple way is to use a single std::vector
for storage, and provide e.g. an at
function or an operator()
for indexing from client code. If you don't yet feel like doing this yourself, then e.g. the Boost library provides a matrix class.