Most efficient way to assign values to maps

前端 未结 6 1278
北荒
北荒 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 20:11

    First, there are semantic differences between [] and insert:

    • [] will replace the old value (if any)
    • insert will ignore the new value (if an old value is already present)

    therefore comparing the two is useless in general.

    Regarding the inserts versions:

    • std::map::value_type is std::pair so no (important) difference between 3 and 4
    • std::make_pair("Bar", 12345) is cheaper than std::pair("Bar", 12345) because the std::string type is a full fledged class with operations to do on copy and "Bar" is just a string literal (thus just a pointer copy); however since at the end you do need to create the std::string... it will depend on the quality of your compiler

    In general, I would recommend:

    • [] for updating
    • insert(std::make_pair()) for ignoring duplicates

    std::make_pair is not only shorter, it also respects the DRY guideline: Don't Repeat Yourself.


    For completeness though, the fastest (and easiest) would be emplace (C++11 enabled):

    map.emplace("Bar", 12345);
    

    Its behavior is that of insert, but it constructs the new element in-place.

提交回复
热议问题