Comparing unordered_map vs unordered_set

26,686

Solution 1

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.

Solution 2

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");

Solution 3

How should I access an element in unordered_set (C++17)?

In C++ 17 a new function extract is added to unordered_set. Specially, this is the only way to take move only object out of the set.

https://en.cppreference.com/w/cpp/container/unordered_set/extract

For example if you want third element of your unordered set. Advance the iterator

std::advance(it,2);

Then extarct the value

s.extract(it).value();

Here is the complete code. try on any C++17 compiler.

#include <iostream>
#include <string>
#include <unordered_set>
#include <iterator>

int main()
{
    //CREATE AN OBJECT
    std::unordered_set<std::string> s;

    //INSERT DATA
    s.insert("aee");
    s.insert("bee");
    s.insert("cee");
    s.insert("dee");

    //NEED TO INCLUDE "iterator" HEADER TO USE "std::advance"
    auto it = s.begin();
    std::advance(it,2);

    //USING EXTRACT
    std::string sval = s.extract(it).value();
    std::cout<<sval;
}

Note: if queried for out of bound index, nothing happens. No result. Try changing your code

 //ONLY FOUR ELEMENTS 
 std::advance(it,8);    
 //USING EXTRACT
 std::string sval = s.extract(it).value();
Share:
26,686
Welez
Author by

Welez

Updated on August 25, 2020

Comments

  • Welez
    Welez over 3 years

    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?