如何避免条件的限制 [英] How to avoid banches of if conditions
本文介绍了如何避免条件的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张填充的地图,我需要根据键重新排列。这样的重新安排需要很多如果的条件,我觉得很难看。
请告诉我任何更好的建议。
谢谢
我尝试过:
I've got a filled map, which I need to rearrange according key. Such rearranging requires a lot of 'if' condition, which i found quite ugly.
please advise me any better suggestion.
thanks
What I have tried:
for (auto it = inventory_data.begin(); it != inventory_data.end(); it++){
if(it->first == "device_model"){
hardware_info.set ("model", it->second);
}
if (it->first == "device_serial"){
hardware_info.set ("serialNumber", it->second);
}
if (it->first == "device_revision"){
hardware_info.set ("revision", it->second);
}
if (it->first == "imei_number"){
mobile_info.set ("imei", it->second);
}
if (it->first == "mobile_cellId"){
mobile_info.set ("cellId", it->second);
}
if (it->first == "mobile_iccid"){
mobile_info.set ("iccid", it->second);
}
if (it->first == "msisdn"){
mobile_info.set ("msisdn", it->second);
}
if (it->first == "imsi"){
mobile_info.set ("imsi", it->second);
}
if (it->first == "mcc"){
mobile_info.set ("mcc", it->second);
}
if (it->first == "mnc"){
mobile_info.set ("mnc", it->second);
}
if (it->first == "lac"){
mobile_info.set ("lac", it->second);
}
}
推荐答案
使用switch而不是if。当你有多个条件并且你也知道结果时它是更好的解决方案
use switch instead of if . it is better solution when you have multiple condition and you know result as well
一个替代方案可能是使用 map
,有字符串as 键值和struct(包含要调用的方法和方法参数)为映射值。
An alternative could be using a map
, having the string as key value and a struct (containing the method to call and the method argument) as mapped value.
如何使用a字典来解决这个问题?然后你的整个循环减少到1行,未来的扩展变得非常简单(并且防错)。
How about using a dictionary to resolve this? Your whole loop is then reduced to 1 line, and future extensions become very easy (and error-proof).
这篇关于如何避免条件的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文