Monday 18 December 2017

c++ - How does std::set and std::unordered_set construct elements in place with emplace()?

itemprop="text">

The documentation for both containers
say that emplace() function constructs elements in place,
but how do they know the location of the new element before the element is constructed?



For example,
unordered_set places elements according to their hash
value. How does the unordered_set know the hash value of
the element before it is constructed?



I thought
maybe the emplace function is meant to take rvalues,
calculate the position of the new element and just move the object, but then
insert() can do the same thing.



Answer





Its unspecified precisely how it
works in the spec, but generally what will happen is that a datastructure-internal node
object (rb-tree node or hash bucket node which contains the value) will be constructed
from the arguments, and then that node will be linked into the data structure (into the
the rb-tree for set, into the hash bucket for unordered_set), and in the event that the
value is already present (so not added), the node object will be
destroyed.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...