Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::map not have an insert function of type insert(key &k, val &v)

Why does std::map not support an insert like the following:

std::map<obj1, obj2> map_int;

void insert_map(obj1 &key, obj2 &val)
{
    map_int.insert(key, val);
}

I know that the above is incorrect. I want to know what prevents from designing the insert function like that. It is more intuitive than creating a pair IMO.

like image 305
0xhacker Avatar asked Dec 25 '22 05:12

0xhacker


2 Answers

It's called emplace():

std::map<std::string, std::string> m;

// uses pair's template constructor
m.emplace("d", "ddd");
like image 56
Barry Avatar answered Jan 17 '23 15:01

Barry


In C++17, you can use:

map_int.try_emplace(key, val);

This actually returns some useful information:

std::pair<std::map<obj1, obj2>::iterator, bool> p = map_int.try_emplace(key, val);
  • p.first is an iterator that points to the element with the given key.
  • p.second indicates whether the insertion took place.

You can achieve a similar effect in C++11 with map_int.emplace(key, val), but there are some subtle differences (related to copying/moving of values). Moreover, try_emplace allows for convenient construction of arbitrary elements:

struct X { X(int, char, bool); };

std::map<int, X> m;
m.try_emplace(10, 20, 'x', false);  // constructs X(20, 'x', false) if new

A similar operation in C++11 would look like this:

m.emplace(
    std::piecewise_construct,
    std::forward_as_tuple(10),
    std::forward_as_tuple(20, 'x', false));
like image 39
Kerrek SB Avatar answered Jan 17 '23 16:01

Kerrek SB