Home > other >  Why isn't there a lazy version of `map::insert_or_assign`?
Why isn't there a lazy version of `map::insert_or_assign`?

Time:12-06

map::insert_or_assign seems like it was designed for implementing caches. But it's essentially useless if the value constructor is relatively expensive and the cache miss rate is approximately zero.

Is there a way to use this function in a lazy way to avoid constructing a value that's not going to be used?

CodePudding user response:

Is there a way to use this function in a lazy way to avoid constructing a value that's not going to be used?

The value passed to insert_or_assign is always used:

  • If a key equivalent to k already exists in the container, assigns std::forward<M>(obj) to the mapped_type corresponding to the key k.
  • If the key does not exist, inserts the new value as if by insert, constructing it from value_type(k, std::forward<M>(obj))

The method you're looking for is try_emplace, which will lazily construct an entry from its arguments only if the key is not already present.

  • Related