I want to initialize a Identity Matrix (ones on the main diagonal and zeros elsewhere) with a 2-D array.
I try to implement this with vector
. The code is like this:
vector<vector<int> > matrix;
matrix.resize(n);
for(auto &i: matrix)
i.resize(n);
// initialize...
This is far more complex than just with ordinary array with just int matrix[n][n]
. I don't do this because I want to return this 2-D matrix. So the function is like this :
matrix_type
func(int n)
{
//intialize the matrix
...
}
Because the array in C++11 is like this:
array<Elem,N> arr;
I have no idea how to get the N at runtime. Then I decide to use the vector.
So is there is a better way to handle this?(without using traditional array)
Thanks for the answer. The question can be solved by use
vector<vector<int>> matrix(n, std::vector<int>(n));
And , another question. If I am a stupid guy and I just want to use the interface, that is , I want the return type to be
array<int,n>
. So is there any method to get the N at runtime and return it?