Deepsy
Deepsy

Reputation: 3800

C++ create array with dynamic size

How can I create a array with dinamic size like this:

int sentLen = sentences.size();

double a[sentLen][sentLen];

for (int i = 0; i < sentLen; i++) 
{
    for (int j = 0; j < sentLen; j++)
    {
        a[i][j] = somefunction(i, j);
    }
}

My research led me to malloc which isn't recommended or other too complicated methods. After I realised that size must be constant, I tried using unordered_map, and I have tried the following:

std::unordered_map <int, int, double> a;


for (int i = 0; i < sentLen; i++) 
{
    for (int j = 0; j < sentLen; j++)
    {
        a.insert({ i, j, somefunc(i, j) });
    }
}

but still unsuccessful.

Upvotes: 1

Views: 942

Answers (2)

David G
David G

Reputation: 96790

You're getting an error because you can't use variables as static array sizes. They must be known at compile time. You have to allocate dynamically or use a vector instead.

Upvotes: 1

aschepler
aschepler

Reputation: 72271

You don't really want to use arrays.

std::vector<std::vector<double>> a{
   sentLen, std::vector<double>{ sentLen, 0.0 } };

for (int i = 0; i < sentLen; ++i)
{
    for (int j = 0; j < sentLen; ++j)
    {
        a[i][j] = somefunc(i, j);
    }
}

Upvotes: 1

Related Questions