Search code examples
c++unordered-set

Checking if element exists in unorderd_set before inserting it


I would like to ask if there is any point of checking if element exists in unorderd_set before inserting it? According to documentation:

Each element is inserted only if it is not equivalent to any other element already in the container (elements in an unordered_set have unique values).

So if I'm getting it correctly in my case:

Element *element = new Element;
//...
if ( my_set.find (element) == my_set.end() )
    my_set.insert(element);

It is not required - correct? What actually happens if I try to insert element that is already in the set. Does it do exactly the same check that I am doing?


Solution

  • If you try to insert a value that is already present, the set will remain unchanged. The call will return a pair containing an iterator and Boolean. The Boolean will be false if the item was already present.

    http://en.cppreference.com/w/cpp/container/unordered_set/insert

    Note that in your case where the set contains pointers it will only prevent you from having duplicate pointers, not duplicate contents. For example,

    if your Element object represented an element, like Oxygen, it might contain a value for the atomic number and a string for the name. If you only want oxygen to appear once, a set of pointers will not automatically do this.