Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top