0

In my thought, emplace is always a better option than insert, because in some case emplace could save one time of ctor and in other cases it could directly replace insert with the same invoking form.

But now I have a map and add an element into it with insert with initialize_list

map<string, map<int,int>> m1;
if (auto it = m1.find("c1"); it == m1.end()){
    m1.insert({ "c1", {{10, 1}} });
}

But with emplace I could not think of any way that as consice as insert and still get the benifits what emplace provides.Like below? It would be ill-formed and compiles in error.

auto [it, inserted] = m1.try_emplace("c1", 10, 1);

So how to emplace in my case? And is it true that emplace is always better than insert?

f1msch
  • 509
  • 2
  • 12
  • 1
    You seem to define "better" as "more performant" sometimes, and as "requires less typing" other times. What criterion do you wish to optimize for? – Igor Tandetnik Feb 07 '23 at 15:46
  • @IgorTandetnik both better, but more on "more performant" – f1msch Feb 08 '23 at 06:53
  • I do believe `emplace` always performs the same or better; I can't think of a scenario where `insert` would win. Well, maybe if you copy a key/value pair from one map to another, and thus already have it in the right form for `insert`. To make `emplace` work with your example, you'd have to write `m1.emplace("c1", map{{10, 1}});` – Igor Tandetnik Feb 08 '23 at 22:23

0 Answers0