首先,有人可以澄清一下,在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;
int
-- 这只是将其设置为 0。可能比重新散列键更快。 - Cory Nelson