简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM