C++创建具有动态大小的数组

C++ create array with dynamic size

本文关键字:数组 动态 创建 C++      更新时间:2023-10-16

我如何创建一个像这样的普通大小的数组:

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

我的研究让我选择了不推荐的malloc或其他过于复杂的方法。在我意识到大小必须是恒定的之后,我尝试使用unordered_map,并尝试了以下操作:

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

但仍然没有成功。

您并不是真的想要使用数组。

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

由于不能将变量用作静态数组大小,因此会出现错误。它们必须在编译时已知。您必须动态分配或使用向量。