while 和 for 循环中的向量 Push_back 返回 SIGABRT 信号(信号 6)(C++)
我正在制作一个 C++ 游戏,需要我将 36 个数字初始化为一个向量。您无法使用初始值设定项列表来初始化向量,因此我创建了一个 while 循环来更快地初始化它。我想让它从 2 到 10 的每个数字中推回 4 个,所以我使用一个名为 Fourth 的 int 来检查循环的数字是否是 4 的倍数。如果是,它会将推回的数字更改为下一个数字。不过,当我运行它时,我得到了 SIGABRT。不过,这肯定是第四个的问题,因为当我把它拿出来时,它没有发出信号。 程序如下:
for (int i; i < 36;) {
int fourth = 0;
fourth++;
fourth%=4;
vec.push_back(i);
if (fourth == 0) {
i++;
}
}
请帮忙!
I'm making a C++ game which requires me to initialize 36 numbers into a vector. You can't initialize a vector with an initializer list, so I've created a while loop to initialize it faster. I want to make it push back 4 of each number from 2 to 10, so I'm using an int named fourth to check if the number of the loop is a multiple of 4. If it is, it changes the number pushed back to the next number up. When I run it, though, I get SIGABRT. It must be a problem with fourth, though, because when I took it out, it didn't give the signal.
Here's the program:
for (int i; i < 36;) {
int fourth = 0;
fourth++;
fourth%=4;
vec.push_back(i);
if (fourth == 0) {
i++;
}
}
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有初始化
i
。使用for (int i = 0; i<36;)
。此外,循环体的每次迭代都会分配一个新变量forth
。因此,测试fourth==0
将始终产生false
。我会使用最直接的方法:
我要做的唯一优化是确保在进入循环之前向量的容量足够。我会将其他优化留给编译器。我的猜测是,你通过省略内循环获得的东西,你会因为频繁的模除法而失去。
You do not initialize
i
. Usefor (int i = 0; i<36;)
. Also, a new variableforth
is allocated on each iteration of the loop body. Thus the testfourth==0
will always yieldfalse
.I would use the most straight forward approach:
The only optimization I would do is making sure that the capacity of the vector is sufficient before entering the loop. I would leave other optimizations to the compiler. My guess is, what you gain by omitting the inner loop, you lose by frequent modulo division.
您没有初始化 i,并且您在每次迭代中重置第四个。另外,根据您的 for 循环条件,我认为它不会执行您想要的操作。
我认为这应该有效:
You did not initialize i, and you are resetting fourth in every iteration. Also, with your for loop condition, I do not think it will do what you want.
I think this should work:
我已经能够创建静态数组声明并在初始化时将该数组传递到向量中,没有问题。也很干净:
适用于常量,但尚未尝试使用非常量数组。
I've been able to create a static array declaration and pass that array into the vector at initialization without issue. Pretty clean too:
Works with constants, but haven't tried it with non const arrays.