【问题标题】:"Jump to case label" error when using vectors inside switch statement. [duplicate]在 switch 语句中使用向量时出现“跳转到大小写标签”错误。 [复制]
【发布时间】:2013-09-02 05:50:36
【问题描述】:

这是代码,当我添加另一种情况或默认值时,会出现几个错误。我找不到任何基本错误,例如缺少分号左右,并且当我只有一个案例时代码可以正常工作。我搜索了开关教程,但我没有发现任何关于向量和开关语句混合是一个问题。

int main()
{
int r; 
while (cin >> r)
{
    switch (r) 
    {
       case 3:
    int y = 0;
    cout << "Please enter some numbers, and I will put them in order." << endl; 
    vector<int> nums;
    int x;
    while(cin >> x)
    {
        nums.push_back(x);
        y++;
    }
    sort(nums.begin(), nums.end());
    int z = 0;
    while(z < y)
    {
        cout << nums[z] << ", ";
        z++;
        if(z > 23)
            cout << "\n" << "User... What r u doin... User... STAHP!" << endl;
    }
    cout << "\n" << "You entered "<< nums.size() << " numbers." << endl;
    cout << "Here you go!" << endl;
    break;

    //In the following line I get the "jump to case label" error. 
    //I use Dev C++ software.

       case 4:
    cout << "it works!!!" << endl;
    break; 
    }
}
system ("PAUSE");
return 0;
}

我错过了什么?

【问题讨论】:

  • 没有。我没有找到那个问题,也没有创建它。
  • 关键是它解决了你的问题。现在,当其他人来查看您的问题时,他们可以找到指向该问题的链接,其中包含很多很好的答案。

标签: c++ vector switch-statement


【解决方案1】:

在案例中添加另一个范围:

switch(n) 
{
case 1:
    {
        std::vector<int> foo;
        // ...
        break;
    }
case 2:
    // ...
default:
    // ...
}

额外的作用域限制了向量对象的生命周期。如果没有它,跳转到 case 2 将跳过对象的初始化,但稍后必须将其销毁,这是非法的。

【讨论】:

  • 或者将代码下推到它自己的函数中。
  • 这有帮助,谢谢。我是否必须在每个包含两行或多行的“案例”中创建一个新范围?
  • @AttilaHerbert:不,你只需要一个作用域,当你……嗯,需要一个作用域。例如。当你有非平凡的局部变量时。
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 2013-04-21
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多