首先,有人可以澄清在 C++ 中使用 [] 运算符与用于查找的 unordered_map 是否包含对 find() 方法的调用,还是使用 [] 运算符比 find() 更快?
其次,在下面的代码中,我怀疑在键不在 unordered_map 中的情况下,我正在通过该行执行第二次查找,map[key] = value
以便替换使用 [] 运算符在此处创建的默认值密钥不存在。
这是真的吗,如果是这样,有没有一种方法(可能通过使用指针或其他东西)我可能在任何情况下都只执行一次查找(可能通过存储放置值/读取值的地址)和仍然实现相同的功能?显然,如果是这样,这将是一个有用的效率改进。
这是修改后的代码摘录:
int stored_val = map[key]; // first look up. Does this wrap ->find()??
// return the corresponding value if we find the key in the map - ie != 0
if (stored_val) return stored_val;
// if not in map
map[key] = value;
/* second (unnecessary?) look up here to find position for newly
added key entry */
return value;