1

std::map has the member function

template <class P> pair<iterator,bool> insert (P&& val);

which we use e.g. like so:

my_map.insert(std::make_pair(k, v));

Question is, why isn't there a variant of insert() which just takes a key and a value, i.e.

pair<iterator,bool> insert (K&& key, V&& value);

(with K and V being the template parameters of the map of course) which we would use e.g. like so:

my_map.insert(k, v);

That seems to me perfectly reasonable to have.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
einpoklum
  • 118,144
  • 57
  • 340
  • 684

2 Answers2

2

This was added in C++11 with the emplace members for all containers, which for map has the signature

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • emplace and insert are two different things - one of them gets values, the other gets constructor arguments. Can you explain how you believe `emplace()` is the same as my suggested variant of `insert()`? – einpoklum Dec 15 '15 at 20:26
  • @einpoklum the Standard Container requirements summarized table 102 of [N4567](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4567.pdf) state that `emplace` forwards its arguments to the constructor of a container's `value_type`. For `std::map`, this means that `emplace(k,v)` will insert a `std::pair`. – TemplateRex Dec 15 '15 at 21:46
0

If you're looking for a more obvious syntax, you can perform the same insertion using the key and values as separate entities like this:

my_map[k] = v;

Granted, this is two separate operations. An insert followed by an assignment so it may not be as efficient as a single insert. But then again, maps store store their entries as pairs so a call to an insert(k, v) function would probably wind up creating a pair<k, v> anyway.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • Thanks, but - that's not what I was asking. I know about `operator[]` - and I also know it [has its problems](http://stackoverflow.com/a/327289/1593077). – einpoklum Dec 12 '15 at 21:40