有一段时间我一直在想,因为它似乎在我经验不足的代码中突然出现了很多。
我有一些经常使用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;
}
}
每条语句中唯一变化的是队列变量。有没有什么巧妙的方法来压缩这种重复的代码?
发布于 2012-04-24 04:44:27
将你的队列存储在一个向量中。
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
发布于 2012-04-24 04:51:24
std::vector<std::queue<someType> > queues (5);
//toSwitchOn is of type size_t and zero indexed.
...
if (toSwitchOn < queues.size())
queue [toSwitchOn].push (newValue); //0 - 1 = undefined land...
else //default switch case
发布于 2012-04-24 05:09:45
显而易见的答案是用要打开的东西的vector
或map
查找来替换switch
。
然而,我认为整数和向量索引之间的耦合是一个泄漏的接口。
我想知道这个函数的调用者是如何知道要使用哪个整数值的。谁告诉他们该用什么?它们是否只是被赋予了一个对Storage
对象的引用呢?
替换:
int function_telling_which_index_to_use_for_storage();
通过以下方式:
Storage* storage_to_use();
然后你可以说:
Storage* storage = storage_to_use();
// ...
storage->store(posx, posy);
记住:封装,封装,封装。
https://stackoverflow.com/questions/10287980
复制相似问题