문제

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!

도움이 되었습니까?

해결책

You do not initialize i. Use for (int i = 0; i<36;). Also, a new variable forth is allocated on each iteration of the loop body. Thus the test fourth==0 will always yield false.

I want to make it push back 4 of each number from 2 to 10

I would use the most straight forward approach:

for (int value = 2; value <= 10; ++value)
{
  for (int count = 0; count < 4; ++count)
  {
    vec.push_back(value);
  }
}

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.

다른 팁

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:

int fourth = 0;
for (int i = 2; i<=10;) {
  fourth++;
  fourth%=4;
  vec.push_back(i);
  if (fourth==0) {
     i++;
  }      
}

I've been able to create a static array declaration and pass that array into the vector at initialization without issue. Pretty clean too:


const int initialValues[36] = {0,1,2...,35};
std::vector foo(initialValues);

Works with constants, but haven't tried it with non const arrays.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top