What is the preferred/idiomatic way to insert into a map?

前端 未结 9 1451
感动是毒
感动是毒 2020-11-28 18:45

I have identified four different ways of inserting elements into a std::map:

std::map function;

function[0] = 42;
function.inse         


        
9条回答
  •  执念已碎
    2020-11-28 19:11

    The first version:

    function[0] = 42; // version 1
    

    may or may not insert the value 42 into the map. If the key 0 exists, then it will assign 42 to that key, overwriting whatever value that key had. Otherwise it inserts the key/value pair.

    The insert functions:

    function.insert(std::map::value_type(0, 42));  // version 2
    function.insert(std::pair(0, 42));             // version 3
    function.insert(std::make_pair(0, 42));                  // version 4
    

    on the other hand, don't do anything if the key 0 already exists in the map. If the key doesn't exist, it inserts the key/value pair.

    The three insert functions are almost identical. std::map::value_type is the typedef for std::pair, and std::make_pair() obviously produces a std::pair<> via template deduction magic. The end result, however, should be the same for versions 2, 3, and 4.

    Which one would I use? I personally prefer version 1; it's concise and "natural". Of course, if its overwriting behavior is not desired, then I would prefer version 4, since it requires less typing than versions 2 and 3. I don't know if there is a single de facto way of inserting key/value pairs into a std::map.

    Another way to insert values into a map via one of its constructors:

    std::map quadratic_func;
    
    quadratic_func[0] = 0;
    quadratic_func[1] = 1;
    quadratic_func[2] = 4;
    quadratic_func[3] = 9;
    
    std::map my_func(quadratic_func.begin(), quadratic_func.end());
    

提交回复
热议问题