I have a function that takes in the number of rows and columns and initialises a vector of vector with default values of the object ‘cell’ and return the pointer to that vector.
//Cell class
class cell{
public:
int cost, parent;
cell(int cost = 0, int parent = 0) : cost(cost), parent(parent){}
}
//The initialisation function
vector<vector<cell> >* init_table(int n_rows, int n_cols){
//Error line
vector<vector<cell> >* table = new vector<vector<cell>(n_cols)> (n_rows);
//Some(very few) special cells need a different value so I do that here
return table; //Return the pointer
}
It seems the compiler resolves (n_cols)> (n_rows) like a > operation and not create n_cols copies of cell objects and n_rows copies of vector objects. How can I initialise the vector without manually looping through and pushing default valued cells in the vector?
Since C++ compilers usually have return value optimization, you can just do simply
and writing
will be as efficient as “new”-ing a vector, but this is safer.