As of C++11, you have two major additional options. First, you can use insert()
with list initialization syntax:
function.insert({0, 42});
This is functionally equivalent to
function.insert(std::map<int, int>::value_type(0, 42));
but much more concise and readable. As other answers have noted, this has several advantages over the other forms:
- The
operator[]
approach requires the mapped type to be assignable, which isn't always the case.
- The
operator[]
approach can overwrite existing elements, and gives you no way to tell whether this has happened.
- The other forms of
insert
that you list involve an implicit type conversion, which may slow your code down.
The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr
values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.
Second, you can use the emplace()
method:
function.emplace(0, 42);
This is more concise than any of the forms of insert()
, works fine with move-only types like unique_ptr
, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace
methods aren't usually used that way.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…