2012-04-23 73 views
0

我曾经想过的一段时间,因为它似乎出现在我的经验丰富的代码相当多。凝聚开关语句?

我有一些使用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; 
    } 


} 

每个语句中唯一改变的是队列变量。有没有一些巧妙的方法来压缩这种重复的代码?

+7

使用队列数组? – 2012-04-23 20:43:56

+0

从外观上看,你有全局队列。您应该将它们传递给函数。用矢量这很容易;有一个类型为'std :: vector >&'的参数。 – chris 2012-04-23 20:54:43

回答

5

将你的队列存储在一个向量中。

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 
+1

如果'toSwitchOn'不在1和5之间,原始代码什么也不做。你的代码不正常。 – hvd 2012-04-23 20:45:32

+0

@ hvd,现在应该会更好,谢谢。 – chris 2012-04-23 20:45:50

+0

你编辑过的版本对我来说很好:) – hvd 2012-04-23 20:47:56

0
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 
+0

如果你参考了我的答案,我只是考虑了'toSwitchOn'在范围[1,5]中,这是交换机处理的内容。 – chris 2012-04-23 20:52:51

0

最明显的答案是与开机的事情vectormap查找替换switch

但是,我看到整数和向量索引之间的耦合作为泄漏接口。

我想知道这个函数的调用者知道使用哪个整数值。谁告诉他们要使用什么?他们是否可以参考Storage对象?

替换:

int function_telling_which_index_to_use_for_storage(); 

有了:

Storage* storage_to_use(); 

然后你就可以说:

Storage* storage = storage_to_use(); 
// ... 
storage->store(posx, posy); 

记住:封装,封装,封装。