Most efficient way to assign values to maps

前端 未结 6 1290
北荒
北荒 2021-02-07 19:30

Which way to assign values to a map is most efficient? Or are they all optimized to the same code (on most modern compilers)?

   // 1) Assignment using array ind         


        
6条回答
  •  一整个雨季
    2021-02-07 19:54

    1) may be slightly slower than the other methods because std::map::operator[] first default-creates the object if it doesn't already exist, then returns a reference that you can use operator= on to set your desired value, i.e. two operations.

    2-4) should be equivalent since map::value_type is a typedef to std::pair for the same types, and therefore make_pair is also equivalent. The compiler should treat these identically.

    Also note that performance can be increased further if you need to both check for existence (e.g. to perform special logic depending on whether it exists or not) and then also insert it, by using map::lower_bound to first get a hint to where the element should be, so map::insert does not have to search the whole map again:

     // get the iterator to where the key *should* be if it existed:
     std::map::iterator hint = mymap.lower_bound(key);
    
     if (hint == mymap.end() || mymap.key_comp()(key, hint->first)) {
         // key didn't exist in map
         // special logic A here...
    
         // insert at the correct location
         mymap.insert(hint, make_pair(key, new_value));
     } else { 
         // key exists in map already
         // special logic B here...
    
         // just update value
         hint->second = new_value;
     }
    

提交回复
热议问题