Home > Software engineering >  initialize array of pointer and matrix
initialize array of pointer and matrix

Time:10-26

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} };

CodePudding user response:

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.

CodePudding user response:

If you really want to dynamically create an array yourself then do what @Vlad from Moscow recommends:

int* arr = new int [5] {1, 2, 3, 4, 5};

or:

int* arr = new int [5];
std::iota( arr, arr   5, 1 ); // also std::fill or std::generate

But, 99% of the time, using std::vector is almost better every way.

Your code would look like this:

std::vector<int> arr{1, 2, 3, 4, 5};
// if you know the size of the array at runtime, then do this
arr.resize(5 /* size of the array at runtime */)

Even better, if you know the size of the array at compile time then std::array is your best friend.

std::array<int, 5 /* size of the array at compile time */> arr{1, 2, 3, 4, 5};

CodePudding user response:

Here is an example using std::make_unique to avoid new/delete. However as you can see, the array size must be manually maintained. So you're still better of using std::vector or std::array

#include <algorithm>
#include <iostream>
#include <memory>

// allocate with make_unqiue and initialize from list
template<typename type_t, std::size_t N>
auto make_array(const type_t (&values)[N])
{
    std::unique_ptr<type_t[]> array_ptr = std::make_unique<type_t[]>(N);
    for (std::size_t n = 0; n < N;   n) array_ptr[n] = values[n];
    return array_ptr;
}

int main() 
{
    auto array_ptr = make_array({ 1,2,3,4,5 });

    for (std::size_t n = 0; n < 5;   n)
    {
        std::cout << array_ptr[n] << " ";
    }

    // std::unique_ptr will take care of deleting the memory
}
  • Related