I want to initialize array of pointer.(not a normal array) But this doesn't work.
int* arr = new int [5];
arr = {1,2,3,4,5};
Also I don't want to do it like this:(Because if the size changes I have to change the code)
arr[0] = 1; arr[1] = 2; ...
Is there an easy way to do this? what about a matrix?
int** mat = ...
mat = { {1,2} , {3,4} }
And also I don't want initialize like this: (Because when I want to pass the matrix to a function there are some limits (For example: If size changes, I have to change function defenition))
int mat[2][2] = { {1,2} , {3,4} };
You can write for example
int* arr = new int [5] { 1, 2, 3, 4, 5 };
Or for example you could use the algorithm std::iota
like
int* arr = new int [5];
std::iota( arr, arr + 5, 1 );
or some other algorithm as for example std::fill
or std::generate
.
If the array will be reallocated then it is much better in this case to use the standard container std::vector<int>
.
(For example: If size changes, I have to change function defenition))
You can define the function as a template function where the size of an array will be a template non-type parameter.