它说我的 vector 超出了 ArrayD 的范围。但我不明白为什么。其他一切都有效。 Is 表示 vector 在 double deez 之后超出范围。因此,它不会完全提升。
使用命名空间标准;
void hello();
无效文件();
双 x, y, z;
双P,B;
整数 E = 0;
双V[16];
双C[16];
双D[16];
整数 m, n;
主要内容()
{
Infile();
return 0;
无效文件()
{
ifstream fileA("P_matrix.txt");
ifstream fileB("b_matrix.txt");
ifstream fileC("d_matrix.txt");
vector<double>ArrayP;
vector<double>ArrayB;
vector<double>ArrayD;
cout << "P Matrix Values \n";
while (fileA.good())
{
fileA >> P;
ArrayP.push_back(P);
}
for (int i = 0; i<ArrayP.size(); i++)
{
cout << ArrayP[i] << ",";
}
system("pause");
cout << "B Matrix Values \n";
while (fileB.good())
{
fileB >> B;
ArrayB.push_back(B);
}
for (int j = 0; j < 16; j++)
{
cout << ArrayB[j] << ",";
}
system("pause");
while (fileC.good())
{
fileC >> D;
ArrayD.push_back(D);
}
for (int k = 0; k <16; k++)
{
cout << ArrayD[k] << ",";
}
system("pause");
for (int m = 0; m < 16; m++)
{
V[m] = ArrayP[m] * ArrayB[m];
cout << V[m] << ",";
}
system("pause");
for (int n = 0; n < 16; n++)
{
C[n] = V[n] * ArrayD[n];
cout << C[n] << ",";
}
//outfile.close();
system("pause");
double deez;
for (int d = 0; d < 16; d++) //acscending
{
for (int q = 0; q < 16; q++)
{
if (ArrayD[q] < ArrayD[q - 1])
{
deez = ArrayD[q];
ArrayD[q] = ArrayD[q - 1];
ArrayD[q - 1] = deez;
}
}
}
for (int q = 0; q < 16; q++)
cout << C[q] << ",";
system("pause");
double nutz;
for (int d = 0; d < 16; d++) //descending
{
for (int q = 0; q < 16; q++)
{
if (V[q] < V[q + 1])
{
nutz = V[q];
V[q] = V[q + 1];
V[q + 1] = nutz;
}
}
}
for (int q = 0; q < 16; q++)
cout << V[q] << ",";
system("pause");
return;
最佳答案
此处,q 从零开始,因此您正试图访问索引 [-1]。
ArrayD[q - 1]
当遍历 ArrayP 时,你正确地做:
for (int i = 0; i<ArrayP.size(); i++)
但是对于 ArrayB 和 ArrayC,您似乎假设这些数组中只有 16 个元素(您确定吗?)。我看不到任何证据表明数组仅限于在代码中始终包含 16 个元素,因此这也可能是问题所在。
再后来,您似乎假设所有这些数组都有 16 个元素?
for (int m = 0; m < 16; m++)
{
V[m] = ArrayP[m] * ArrayB[m];
cout << V[m] << ",";
}
这些是可能导致超出范围错误的明显位置。
关于c++ - vector 超出范围,但为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925221/