简体   繁体   English

C ++中的语句

[英]Statements in C++

In C++ want to write something like this 在C ++中想写这样的东西

int Answer;
if (Answer == 1 || Answer == 8 || Answer == 10) 

and so on, is it any way to make code shorter without repeating variable always? 等等,是否可以在不重复变量的情况下缩短代码?

Try: 尝试:

 switch (Answer) {
     case 1:    // fall through
     case 8:    // fall through
     case 10:
         // ... do something
         break; // Only need if there are other case statements.
                // Leaving to help in mainenance.
 }

For readability I'd encapsulate the logic in descriptively-named functions. 为了便于阅读,我将逻辑封装在描述性命名的函数中。 If, say, your answers are things with a particular color, and answers 1, 8, and 10 are green things, then you can write that logic as 例如,如果您的答案是具有特定颜色的事物,并且答案1,8和10是绿色事物,那么您可以将该逻辑写为

bool ChoiceIsGreen(int answer)
{
    return (answer == 1 || answer == 8 || answer == 10);
}

Then your function becomes 然后你的功能变成了

if (ChoiceIsGreen(Answer))
{
    // offer some soylent green
}

If you have a lot of choices like this, I can see it getting hard to read if you have a lot of raw numbers all over the place. 如果你有很多这样的选择,如果你有很多原始数据,我会发现它很难读。

If and only if you need to optimise for code size manually, and Answer is guaranteed to be positive and less than the number of bits in an int, you might use something like 当且仅当您需要手动优化代码大小,并确保Answer为正且小于int中的位数时,您可能会使用类似的东西

if ( ( 1 << Answer ) & 0x502 )

But normally you don't want to obscure your logic like that. 但通常你不想这样模糊你的逻辑。

You could put the values into a container and search the container. 您可以将值放入容器中并搜索容器。
Sounds like a std::set would be a wise choice: 听起来像std::set将是明智的选择:
if answer is in the set of (1, 8, 10) then do.... 如果答案在(1,8,10)的集合中那么....

Remember that a std::set must be initialized during run-time, unlike numeric constants or an array of numeric constants. 请记住, std::set必须在运行时初始化,这与数字常量或数字常量数组不同。 Before making any performance changes, first get the program working correctly, then profile if necessary , that is only if the program demands performance optimization. 在进行任何性能更改之前,首先让程序正常工作,然后在必要时进行配置,这只有在程序需要性能优化时才能进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM