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?
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, assignsstd::forward<M>(obj)
to themapped_type
corresponding to the keyk
.
- 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.