gpt4 book ai didi

c++ - 压缩 switch 语句?

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:44 25 4
gpt4 key购买 nike

我想知道了一段时间,因为它似乎经常出现在我经验不足的代码中。

我有一些代码经常使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com