实例化一个std ::升压的矢量:: multi_array ..为CPP大师融化大脑?
-
14-11-2019 - |
题
我觉得我与实例化对象混淆了..很好......不是正确的对象,因为世代odicetagcode语句进行编译错误。我的背景是在Python和Java中,我陷入了C ++的方式,它的创建不是类的对象。
我正在从c#和机器学习翻译算法,它使用多维数组数组。
c#代码:
public double Learn(int[][] observations, int symbols, int states, ...
// ...
double[][, ,] epsilon = new double[N][, ,]; // also referred as ksi or psi
double[][,] gamma = new double[N][,];
for (int i = 0; i < N; i++)
{
int T = observations[i].Length;
epsilon[i] = new double[T, States, States];
gamma[i] = new double[T, States];
}
.
我决定使用多维数组的Boost库,我有:
typedef boost::multi_array<double, 2> matrix2D;
typedef boost::multi_array<double, 3> matrix3D;
vector<matrix3D> epsilon;
vector<matrix2D> gamma;
cout << "HMM::learn >> before" << endl;
for (int i = 0; i < N; i++)
{
int T = observations[i].size();
epsilon[i] = matrix3D(boost::extents[T][states][symbols]);
gamma[i] = matrix2D(boost::extents[T][states]);
}
.
,我得到这个运行时错误:
hmm ::学习>>之前 std :: bad_alloc'什么():std :: bad_alloc
解决方案
The vectors have no space allocated (well it may be reserved already but you can't reference it with the array indexers). Change the lines:
epsilon[i] = matrix3D(boost::extents[T][states][symbols]);
gamma[i] = matrix2D(boost::extents[T][states]);
To:
epsilon.push_back(matrix3D(boost::extents[T][states][symbols]);
gamma.push_back(matrix2D(boost::extents[T][states]);
that should solve it. In your case since you know the array size you should reserve that much space in the vectors so that it reduces the reallocations needed:
epsilon.reserve(N);
gamma.reserve(N);
不隶属于 StackOverflow