替代使用switch语句C ++

时间:2018-01-09 01:52:37

标签: c++ arrays switch-statement

我在switch声明中有大约40个案例。它检查的值是一个数字,它是来自用户连接的两个输入,因此如果它们输入3和4,它将34传递给switch语句。每个switch语句都将该值传递给另一个函数,然后该函数根据连接值返回素材长度。什么是更好的方法呢?

我在考虑某种类型的数组,我可以for循环查找我想要的值吗?

修改:代码段

void calcFootages2(const int z) {
    std::cout << "\n\nThe value of Z: " << z;
    switch (z) {
        default:
            std::cout << "\nYour input of " << z << " was invalid or something went wrong, please retry.";
            locChoose();
            break;
        case (12):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (21):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (23):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (32):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (34):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
    }
}

calcfootages功能 -

int calcFootages3(const int x) {
        if (x == 12 || x == 21) {
            return 10;
        }
        else if (x == 23 || x == 32) {
            return 11;
        }
    }

因此,返回11最终将是正确的素材长度,然后将其传递回switch语句,以便它可以将其显示给用户。我拿走了大部分的陈述,因为它们几乎都是一样的。

我希望我能正确格式化代码。

1 个答案:

答案 0 :(得分:3)

您可以分开检查有效的规格和素材计算,例如像这样:

std::vector<int> const valid_specs = {12, 21, 23, 32, 34};

if( find( valid_spec.begin(), valid_spec.end(), z ) == valid_spec.end() )
{
    cout << "Your input of " << z << " was invalid or something went wrong, please retry.";
}
else
{
    cout << "This will require a jumper " << calcFootages3(z) << " feet long.";
}

免责声明:编码器未检查代码。