Jam*_* MV 0 c++ switch-statement
我曾经想过一段时间,因为它似乎在我的经验丰富的代码中出现了很多.
我有一些代码使用了很多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;
}
}
Run Code Online (Sandbox Code Playgroud)
每个语句中唯一改变的是队列变量.是否有一些巧妙的方法来压缩这种重复的代码?
将您的队列存储在矢量中.
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
244 次 |
最近记录: |