额外的 std::map::contains 调用与处理异常?

Gri*_*lik 0 c++ stl stdmap c++20

c++中什么效率更高?

if (my_map.contains(my_key)) return my_map.at(my_key);
Run Code Online (Sandbox Code Playgroud)

或者

try { return my_map.at(my_key); } catch (std::out_of_range e) { ... }
Run Code Online (Sandbox Code Playgroud)

Art*_*yer 6

最有效的方法是使用std::map<>::find

if (auto it = my_map.find(my_key); it != my_map.end()) return *it;
Run Code Online (Sandbox Code Playgroud)

contains这避免了对follow by 的双重查找以及对 if throwsat的昂贵的异常处理at