我有一段 C 代码:
mel[i] = malloc(sizeof(double)*mellength[i]);
memcpy(mel[i],&temp[melstart[i]],mellength[i]*sizeof(double));
我将其转换为 C++ 并使用向量而不是数组:
vector< vector< double > > mel; // 2D vector
mel[i].resize(mellength[i]);
我有一个名为“temp”(一维)的数组,我想将“temp”中的所有元素复制到向量 mel 中。我试过这个:
for(int k=0; (k < mellength[i]); k++)
{
mel[i][k] = temp[i];
cout << mel[i][k] << endl;
}
但是它不起作用,只是打印出不应该存在的值。如果您想深入了解我正在尝试做的事情,我已经包含了 C 函数以及下面的 C++ 函数。
C函数:
void Setup_Mel(int fft_size, int sample_rate) {
int i,j,k,tap;
double fmax;
double dphi;
double fsample;
double freq;
double temp[fft_size/2];
fmax=2595*log10(8000.0f/700+1);
dphi = fmax/17;
freq = (double)sample_rate/fft_size;
for (i=0; i<16; i++) {
melstart[i]=fft_size/2;
mellength[i]=0;
memset(temp,0,sizeof(double)*fft_size/2);
for (j=0; j<fft_size/2; j++) {
fsample = 2595*log10(freq*j/700 + 1);
if ((dphi*i <= fsample) && (fsample < dphi*(i+1))) temp[j] = (fsample-dphi*i)/(dphi*(i+1)-dphi*i);
if ((dphi*(i+1) <= fsample) && (fsample < dphi*(i+2))) temp[j] = (fsample-dphi*(i+2))/(dphi*(i+1)-dphi*(i+2));
if ((temp[j] != 0) && (melstart[i] > j)) melstart[i] = j;
if (temp[j] != 0) mellength[i]++;
}
mel[i] = malloc(sizeof(double)*mellength[i]);
memcpy(mel[i],&temp[melstart[i]],mellength[i]*sizeof(double));
// for (k=0; k<mellength[i]; tap++,k++) printf("mel filter: %d, %d, %d, %f, %f\n",i,melstart[i]+k,tap,mel[i][k],(melstart[i]+k)*freq);
}
}
C++ 代码:
void setUp_Mel(int fft_size, int sample_rate, vector< vector< double > > &mel, int *melstart, int *mellength)
{
double fmax;
double dphi;
double fsample;
double freq;
double temp[fft_size/2];
fmax = 2595*log10(8000.0f/700+1);
dphi = fmax / 17;
freq = (double)sample_rate/fft_size;
for(int i=0; (i < 16); i++)
{
melstart[i] = fft_size/2;
mellength[i] = 0;
double temp[fft_size/2];
//double *temp = new double[fft_size/2];
for(int j=0; (j < fft_size/2); j++)
{
fsample = 2595*log10(freq*j/700 + 1);
if ((dphi*i <= fsample) && (fsample < dphi*(i+1)))
{
temp[j] = (fsample-dphi*i)/(dphi*(i+1)-dphi*i);
}
if ((dphi*(i+1) <= fsample) && (fsample < dphi*(i+2))) {
temp[j] = (fsample-dphi*(i+2))/(dphi*(i+1)-dphi*(i+2));
}
if ((temp[j] != 0) && (melstart[i] > j))
{
melstart[i] = j;
}
if (temp[j] != 0) mellength[i]++;
}
mel[i].resize(mellength[i]);
for(int k=0; (k < mellength[i]); k++)
{
mel[i] = temp[i];
}
}
}