为什么 std::vector 在 C++ 中没有给出任何输出

Why is the std::vector not giving any outputs in c++

我不明白为什么,但在我将 class 指针放入数组后 std::vector 没有给出任何信息。

// runs at start
void States::AssignState(GameState* state) {
    _nextVacentState++;
    _states.push_back(state);
}

// executes in a loop
void States::ExecuteCurrentState() {
    // protection incase there is nothing in the array or the current state is not grater than the size of the array (not the problem after i nerrowed the problem down)
    if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; // there is no states
    if (_currentState >= _states.size() - 1) std::cout << "Error: Current State is grater than all possable states" << std::endl; return;
    
    // The program just freezes at this and i can figure out why
    _states[0]->tick();
    std::printf("S");
}

这是我建议养成对所有 if 语句使用花括号的习惯的原因之一,即使是那些位于一行中的语句。

问题行:

if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return;

让我们添加一些换行符,使发生的事情更清楚

if (_nextVacentState == 0) 
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
  return;

return 语句被无条件执行,因为 只有 if(_nextVacentState==0) 之后的第一个语句实际上是 if 的一部分。所以编译器执行它就好像它是这样写的:

if (_nextVacentState == 0)
{
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
}
return;

但是,你想要的需要这样写:

if (_nextVacentState == 0) 
{
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
  return;
}

您在接下来的 if 检查 _currentState 中也有同样的问题。