我想知道了一段时间,因为它似乎经常出现在我经验不足的代码中。
我有一些代码经常使用 switch 语句,但它真正做的是每次访问不同的队列。
void store(int toSwitchOn, float posx, float posy){
myDataStruct newValue;
newValue.psX = posx;
newValue.psY = posy;
switch(toSwitchOn){
case 1:
queue1.push(newValue);
break;
case 2:
queue2.push(newValue);
break;
case 3:
queue3.push(newValue);
break;
case 4:
queue4.push(newValue);
break;
case 5:
queue5.push(newValue);
break;
}
}
每个语句中唯一改变的是队列变量。有什么巧妙的方法可以压缩这种重复的代码吗?
最佳答案
将队列存储在 vector 中。
std::vector<std::queue<someType> > queues (5);
//fill vector with your 5 queues
//this replaces the switch:
if (toSwitchOn >= 1 && toSwitchOn <= 5)
queue [toSwitchOn - 1].push (newValue);
else
//default switch case
关于c++ - 压缩 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10287980/