std::string v = GetV();
if(v == "AAA") {
func1();
} else if (v == "BBB" || v == "CCC" || v == "EEE") {
func2();
} else {
func3();
}
基本上,我想像上面的代码一样进行条件处理。由于将来可能会有更多的v值,因此我认为if-else语句不够好。所以我将其替换为map
;
enum v_type {
v_type1,v_type2,v_type3,v_type4
};
string v = GetV();
const static std::map < string,v_type > v_map({
"AAA",v_type1
},{
"BBB",v_type2
},{
"CCC",v_type2
});
auto iter = v_map.find(v);
if (iter == v_map.end()) return;
switch
case (iter->second) {
case v_type1:
func1();
break;
case v_type2:
func2();
break;
}
我认为map(Olog(N))甚至unordered_map都比if-else语句中的字符串比较要快,但要权衡的可能是内存和CPU的映射本身。我对吗?使用map / unorder_map比if-else更好吗?