jeudi 13 avril 2023

Insert in std::map without default empty constructor

I have instances of std::map<std::string,Foo> where I insert and fill data. The class Foo is default-constructible, default-copyable. Then I do it by this (simple) way:

std::map<std::string,Foo> data;
for(std::string const& key : keys)
{
  assert(data.count(key) == 0); // it's assumed that the keys not already exist
  Foo& foo = data[key];
  foo.fill(blahblah);
}

After refactoring, the class Foo lost the default empty constructor. What are the (simple) alternatives to insert and fill data ? For the moment, I replaced by this but I don't know if it's the best/simplier way to refactor the code:

std::map<std::string,Foo> data;
for(std::string const& key : keys)
{
  assert(data.count(key) == 0); // it's assumed that the keys not already exist
  Foo& foo = data.emplace(key, Foo(requirement)).first->second;
  foo.fill(blahblah);
}

I also think it could be possible with insert, insert_or_assign, emplace, emplace_hint, try_emplace. I'm a little bit lost with all the possibilities...

I'm interested in solutions for C++11 or C++17.

Aucun commentaire:

Enregistrer un commentaire