That syntax of:
std::map<int, int> m;
m.insert(std::make_pair(1, 42));
seems a bit crazy.
Why is there no alternative insert(K k, V v)
method which would provide a much saner:
std::map<int, int> m;
m.insert(1, 42);
Yes, I'm aware of m[1] = 42
, but it has its own problems (creating an extra copy of the value object).
I can't tell you why that construct isn't allowed. Perhaps to keep insert
similar to other containers' insert
method. However, since c++11, there is map::emplace that does what you want.
std::map<int, int> m;
m.emplace(1, 42);
m.insert(x, y);
forces a copy of the two parameters; whereas m.insert(std::make_pair(1, 42));
allows the call to get a const& pair
which avoids all copying. That way, map
can contain uncopyable objects (or heavy-duty copy objects)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.