如何创建一个像这样具有动态大小的数组:
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);
}
}
关于C++创建具有动态大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23318747/