2

Here is the code snippet.

Why std::unordered_set<std::vector<int>> does not compile whereas std::unordered_set<int> is ok? Could someone please give me a detailed explanation?

UPDATE: Here is the error messages:

error: use of deleted function 'std::unordered_set<_Value, _Hash, _Pred, _Alloc>::unordered_set() [with _Value = std::vector<int>; _Hash = std::hash<std::vector<int> >; _Pred = std::equal_to<std::vector<int> >; _Alloc = std::allocator<std::vector<int> >]'
    ...

Tips: Sorry, I can't fully understand the error message.

  #include <vector>
  #include <algorithm> 
  #include <unordered_set>
  #include <iostream>
  #include <vector>
  
  int main()
  {
    std::unordered_set<std::vector<int>> set_of_vector;  //Why this one goes wrong?

    std::unordered_set<int> set_of_int;

    return 0;                    
  }
John
  • 2,963
  • 11
  • 33
  • 1
    What is the error message? Search for it online, too! What have you found as requirements for elements of unordered_set? See cppreference.com for example. – Ulrich Eckhardt Feb 08 '22 at 07:42
  • `unordered_set` is a hash table, which requires a hash function (hasher). C++ standard library does not provide hashers for containers. You can use the one from Boost. Live demo: https://godbolt.org/z/P8zh816aY – Daniel Langr Feb 08 '22 at 07:44
  • @UlrichEckhardt updated. – John Feb 08 '22 at 07:45
  • BTW: I searched for "[c++] unordered_set", simple as that. – Ulrich Eckhardt Feb 08 '22 at 07:50
  • @DanielLangr After I have carefully studied your demo code. It seems that I should **also** pass a suitable implementation of **equality comparison** as a third template parameter of std::unodered_set(i.e. something like `std::vector, boost::hash>, boost::compare>` other than `std::vector, boost::hash>>`). **Am I right**? – John Feb 08 '22 at 07:54
  • @John I am not 100% sure but I think the comparison operator for `std::vector` should be fine. What is the difference with `boost::compare`? – Daniel Langr Feb 08 '22 at 08:00
  • @Daniel Langr If I correctly understand you, since there is `operator==()` for `std::vector` in `std c++`, so **I don't have to provide one by myself**. Am I right? – John Feb 08 '22 at 08:05
  • @John Yes, there is. Have you checked the reference? https://en.cppreference.com/w/cpp/container/vector/operator_cmp – Daniel Langr Feb 08 '22 at 08:08
  • @Daniel Langr Thank you for your clarification. With your help, my understanding of this matter is at a different level. The reference is so hard for me to fully understand. – John Feb 08 '22 at 08:10

0 Answers0