2016-11-22 2 views
3

나는 세트가 주문됨을 이해하므로 < 과부하가없는 오브젝트를 추가하면 작업자는 컨테이너를 정렬 된 상태로 유지하기 위해 더 작은 오브젝트를 말할 수 없습니다. 그러나, 왜 unordered_set으로 이것이 가능하지 않은지 나는 이해하지 못한다.C++ 11 : 왜 객체를 unordered_set에 저장할 수 없습니까?

나는 이런 식으로 뭔가하려고하면 :

c:\qt\qt5.1.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\hashtable_policy.h:1070: error: invalid use of incomplete type 'struct std::hash'

c:\qt\qt5.1.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\functional_hash.h:58: error: declaration of 'struct std::hash'

error: no matching function for call to 'std::unordered_set::unordered_set()'

c:\qt\qt5.1.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\hashtable_policy.h:1103: error: no match for call to '(const std::hash) (const someType&)'

c:\qt\qt5.1.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_function.h:208: error: no match for 'operator==' (operand types are 'const someType' and 'const someType')

이유입니다 :

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

using namespace std; 

struct someType{ 
    string name; 
    int code; 
}; 

int main(){ 
    unordered_set <someType> myset; 
    myset.insert({"aaa",123}); 
    myset.insert({"bbb",321}); 
    myset.insert({"ccc",213}); 
    return 0; 
} 

내가 좋아하는 몇 가지 오류를 얻을 수 있습니까?

+0

정확한 코드와 정확한 오류 메시지를 게시 할 수 있습니까? – templatetypedef

+1

그것은 실제 오류가 아닐 것 같습니다. 실제로 '설정'을 사용하지 않으시겠습니까? –

+1

아니요, 순서가 없습니다. 하지만 당신 말이 맞습니다. 정확한 오류는 아닙니다. 방금 전체 코드와 자세한 오류 메시지를 추가하기 위해 편집했습니다. 감사합니다 :) –

답변

7

unordered_set 또는 unordered_map에서 유형을 사용하려면 유형에 대한 해싱 함수가 필요합니다. 일반적인 유형의 경우, int 또는 std::string과 같은 - 해시 함수는 표준 라이브러리에서 제공됩니다. 당신의 유형에 대해이 같은 표준 std::hash를 오버로드 할 수 있습니다

namespace std { 
    template <> struct hash<someType> { 
     size_t operator()(const someType & x) const { 
      std::hash<std::string> h; 
      return h(x.name); 
      // or simply return x.code 
      // or do something more interesting, 
      // like xor'ing hashes from both members of struct 
     } 
    }; 
} 

또 다른 방법은 다음과 같이 오버로드 operator() 함께 자신의 유형을 제공하고 unordered_set에 해시 템플릿 인수로 넣어하는 것입니다

struct someTypeHasher { 
    size_t operator()(const someType& x) const { 
     return x.code; 
    } 
}; 
std::unordered_set<someType, someTypeHasher> myset; 
해시 기반 컨테이너에 대한 이론

좋은 독서 당신이 그것을하지 않고, someType에 대한 operator==에 과부하를해야한다고, 또한 here

, 잊지 마세요 - 그것은 WI 또한 작동하지 않을 것입니다.

+1

'{ "aaa", 123}','{ "aaa", 456}'및'{ "bbb", 456}'가되도록'name'과'code'의 해시를 결합하는 것이 현명합니다. 다른 해시 있습니다. – Zereges