我有我有 x、y、z 坐标和另一个参数 - 能量的对象。具有相同x、y、z坐标的物体的能量要相加。我看过一个程序如何实现它并遵循完全相同的方法,但是,我的程序失败了,我不明白为什么。
概述了方法。
我有一个D类对象的 vector ;
class D; //for the sake of time you will understand the structure of this class as u keep reading
int main()
{
vector< D>cont; //the objects to be summed are stored in this container
vector< D>cont2; //Second container: you will see the need later on
co_ord [100][100][100]; //Declare the range of available x, and z coordinates
for (int z = -49; z<50; z++)
for (int y = -49; y<50; y++)
for (int x = -49; x<50; x++)
co_ord[z][y][x] = -1;
for (int i = 0; i < cont.size(); i++){
int x, y, z, E;
**//PROBLEM AREA!!!**
x = cont[i].getx();//member function of class D : returns x of current obj
y = cont[i].gety();
z = cont[i].gez();
E = cont[i].getE();
if(x>=50){x = 49;}
if(y>=50){y = 49;}
if(z>=50){z = 49;}
if(x<= -50){x = -49;}
if(y<= -50){y = -49;}
if(z<= -50){z = -49;}
if (co_ord[z][y][x] = -1)
{
D obj(x, y, z, E); //create new object of class D
cont2.push_back(obj);
int index = cont2.size();
co_ord[z][y][x] = index - 1; // co_ord[z][y][x] has the storage index of this co-ordinate
}
else {cont2[co_ord[z][y][x]].AddEn(E); //AddEn() is a member function of class D that adds energy to "this" obj;
return 0;
}
}
现在我有两个主要问题:
如果我使用 co_ord[300][300][300],程序会给出一个段错误。如果放在 3 个连续的 for 循环之前,cout 语句将执行,但不会在之后; 当我将 co_ord 的维数减少到 co_ord[100][100][100] 时,这个问题就解决了,我将能够在其他任何地方计算语句。
但是,还有一个奇怪的问题,我仍然不知道为什么会这样。发生这种情况的区域在前面的代码中标记为“问题区域”。基本上发生的事情是 co_ord[z][y][x] 在第一次循环后会给出一些奇怪的值。第一个循环运行良好,即 co_ord[-9][0][1] 将 cout -1,但在第二个循环中,我有像 6783 和其他有时可能高达 8 位数字的值。但这是在第二个循环期间发生的。我已经尝试了我所知道的一切,但我没有成功。
拜托,有人可以提供线索来说明为什么我有上述 2 个错误或解决方法吗?正如我所说,我的系统上运行着完全相似的代码,它是更大应用程序的一部分。在代码中,他们为他们创建的容器类实现了一些内存分配过程,但是他们的过程对我来说很复杂,因此我决定使用标准 c++ 库 vector 来完成。任何帮助将不胜感激。
很抱歉之前发布了错误代码,我已经更正了大部分(我希望所有)拼写错误
最佳答案
If I use co_ord[300][300][300], the program gives a segmentation fault.
这是正常的。假设您有 int a[2]
;它是一个包含两个元素的数组,从零开始(a[0]
、a[1]
)。 a[2]
将是第三个元素,访问它会导致未定义的行为。
co_ord[-9][0][1] will cout -1, but on the second loop, I have values like 6783
和上面类似的问题。如果你有 a[10]
,你可以通过 a[n]
访问它,n 的范围是 [0, 9]。使用负值访问它是未定义的行为。
for (int i = 0; i < cont.size(); i++)
int x, y, z, E;
这是一个空操作,因为 for 没有括号(良好的缩进习惯,您似乎没有,会使错误变得明显)。由于您随后使用了变量 - 这将超出范围 - 我不知道您的程序如何成功编译。除此之外,还有一行 co_ord[300][300][300]
没有类型,也不应该编译。
关于C++ vector 被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4605496/