Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing unordered_map vs unordered_set

First of all, what is the main difference between them?

The only thing i've found is that unordered_set has no operator []. How should i access an element in unordered_set, since there is no []?

Which container is using random access to memory(or both)?

And which one of them faster in any sense or using less memory?

like image 547
Welez Avatar asked Oct 29 '16 15:10

Welez


People also ask

Can we compare 2 unordered maps?

The comparison between unordered_map objects is not affected by the arbitrary order in which they store their elements. Two unordered_maps are equal if they have the same number of elements and the elements in one container are a permutation of the elements in the other container. Otherwise, they are unequal.

Is unordered map better than map?

Insertion performance As you can see, using the unordered_map is substantially faster than the map implementation, even for small numbers of elements.

Is unordered_set faster than set?

For a small number of elements, lookups in a set might be faster than lookups in an unordered_set . Even though many operations are faster in the average case for unordered_set , they are often guaranteed to have better worst case complexities for set (for example insert ).

Why do you use unordered map Why not ordered map?

map is used to store elements as key,value pairs in sorted order. unordered_map is used to store elements as key,value pairs in non-sorted order.


2 Answers

They are nearly identical. unordered_set only contains keys, and no values. There is no mapping from a key to a value, so no need for an operator[]. unordered_map maps a key to a value.

You can use the various find methods within unordered_set to locate things.

like image 187
1201ProgramAlarm Avatar answered Sep 29 '22 23:09

1201ProgramAlarm


you can use iterators to access elements.

unordered_set <string> u{
            "Dog",
            "Cat",
            "Rat",
            "Parrot",
            "bee"
};

for(auto& s:u){
     cout << s << ' ';    
} 

unordered_set<string>::const_iterator point = u.find("bee");
like image 31
Sachith Bathiya Avatar answered Sep 29 '22 23:09

Sachith Bathiya