Firstly could someone clarify whether in C++ the use of the [] operator in conjunction with an unordered_map for lookups wraps a call to the find() method, or is using the [] op
Firstly could someone clarify whether in C++ the use of the [] operator in conjunction with an unordered_map for lookups wraps a call to the Find() method, or is using the [] operator quicker than Find()?
There is no rule for that. An implementation of []
could use find()
, it could perform the lookup by itself or it could delegate the lookup to some private method that is also used by find()
internally.
There is also no guarantee on which one is faster. find()
involves an overhead in constructing and returning an iterator, whereas []
will probably be slower if the key does not exist, as it inserts a new value in this case.
(...) is there a way (perhaps by use of pointers or something) that I might only perform one look up in any case (...)
If the key is not in the map, []
will insert a new default-constructed value, and return a reference. Therefore, you could store that reference to save the second lookup:
int& stored_val = map[key]; // Note the reference
if (stored_val) return stored_val;
// Use the reference to save a second lookup.
stored_val = value;
return value;