2

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).

3
  • 3
    m.emplace(1, 42)? Commented Jan 6, 2017 at 20:54
  • 1
    Consistency and history, I guess. I think map already worked like this in the original STL before it was incorporated into the standard library, and since the container's value type is a pair, using a pair as the parameter type is simply the most logical way. AFAIK, operator[] was an afterthought, designed as a (inconsistent) convenience function exactly to provide the "saner" alternative you are asking for. Commented Jan 6, 2017 at 22:04
  • This question is similar to: Why pair is required to insert into map?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Apr 8 at 9:42

2 Answers 2

5

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); 
Sign up to request clarification or add additional context in comments.

Comments

-2

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)

4 Comments

So creating a pair by std::make_pair does not lead to copying?
Quite the opposite, the make_pair approach encourages creation of incorrectly-typed pair object, which cannot be passed to insert directly and requires an extra conversion, i.e. an extra copy. Your example actually illustartes that popular mistake very well. Your make_pair will create an <int, int> pair, while insert requires a <const int, int> pair. The compiler will not complain because the former is implicitly convertible to the latter. But the conversion will create a temporary copy. So hello, unnecessary copying!
@AnT can you elaborate what is wrong with the make_pair in his example? It is not const enough?
@MK. It has a type of std::pair<int, int> instead of std::pair<const int, int>.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.