我有以下结构:
std::map<int, std::map<int, int>> my_map;
Run Code Online (Sandbox Code Playgroud)
我想检查密钥是否my_map[3][5]存在。
除了以下方法之外,还有更简单/更短的方法吗?
if (my_map.find(3) != my_map.end()) {
std::map<int, int>& internal_map = my_map[3];
if (internal_map.find(5) != internal_map.end()) {
// ... Do something ...
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式稍微改进它:
std::map<int, std::map<int, int>>::iterator it = my_map.find(3);
if (it != my_map.end()){
if (it->second.find(5) != internal_map.end()) {
}
}
Run Code Online (Sandbox Code Playgroud)
在当前的解决方案中,您需要两次查找密钥,这可能比查找一次并将其存储在迭代器中要慢。