Using The [] Operator Efficiently With C++ unordered_map

前端 未结 3 699
走了就别回头了
走了就别回头了 2021-01-31 02:42

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

3条回答
  •  心在旅途
    2021-01-31 03:20

    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;
    

提交回复
热议问题