简体   繁体   English

在开关盒内使用std :: map

[英]Using std::map inside switch case

I have this: 我有这个:

map<string,int> a;
int b;

And i'd like to make this: 我想做这个:

switch(b)
{
  case a["someStr1"]:
  someCode1();
  break;

  case a["someStr2"]:
  someCode2();
  break;

  etc.
}

But it doesn't compiles. 但是它不能编译。 How to implement this correctly? 如何正确实施?

switch conditions need to be constants, so what you want to do here is not possible. switch条件必须为常数,因此您在此处无法执行的操作。

You're better off using some if statements. 您最好使用一些if语句。

switch/case are meant for constants (eg, enum , int s etc.). switch/case用于常量(例如, enumint s等)。
You can use the map<>::iterator to run through the values and compare with b . 您可以使用map<>::iterator遍历这些值并与b比较。

for(map<string,int>::const_iterator it = a.begin(), end = a.end(); it != end; it++)
{
  if(it->second == b)
  {
    ...
    break;
  }
}

This way you can avoid the code duplication for comparison, if your a is large enough. 这样,如果a足够大,则可以避免代码重复进行比较。

Also, you can explore the option of replacing for loop with for_each . 另外,您可以探索用for_each替换for循环的选项。

You can't. 你不能 Expression after case in a switch statement must be integral compile-time constant. switch语句中case之后的表达式必须是整数编译时常数。 So a literal ( 42 ), const int variable initialized with a literal ( const int x = 66 ... case x: ) or enum value. 因此,使用文字( const int x = 66 ... case x: :)或枚举值初始化的文字( 42 ),const int变量。 And thats about it. 就是这样。

The reason this is so strict is efficiency. 如此严格的原因是效率。 Compilers usually create labels for each case and if you know the value for each label at compile time, you can make some nice optimizations that avoid most of the overhead a normal code branching has. 编译器通常会为每种case创建标签,如果您在编译时知道每个标签的值,则可以进行一些不错的优化,从而避免常规代码分支所具有的大部分开销。

In your case just go with if-else: 在您的情况下,请使用if-else:

if(b == a["someStr1"]) {
    //...
} else if(b == a["someStr2"]) {
    //...
}   // and so on

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

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