2009-05-16 10 views
7

Mi piacerebbe vedere un semplice esempio di come sovrascrivere stdext :: hash_compare correttamente, al fine di definire una nuova funzione di hash e un operatore di confronto per il mio tipo definito dall'utente. Sto usando Visual C++ (2008).Come usare stdext :: hash_map?

risposta

1

Qui si va, ad esempio da MSDN

+2

Questo esempio non sovraccarica la funzione hash. – batty

8

In questo modo si può fare

class MyClass_Hasher { 
    const size_t bucket_size = 10; // mean bucket size that the container should try not to exceed 
    const size_t min_buckets = (1 << 10); // minimum number of buckets, power of 2, >0 
    MyClass_Hasher() { 
      // should be default-constructible 
    } 
    size_t operator()(const MyClass &key) { 
      size_t hash_value; 
      // do fancy stuff here with hash_value 
      // to create the hash value. There's no specific 
      // requirement on the value. 
      return hash_value; 
    } 

    bool operator()(const MyClass &left, const MyClass &right) { 
      // this should implement a total ordering on MyClass, that is 
      // it should return true if "left" precedes "right" in the ordering 
    } 
}; 

Poi, si può semplicemente utilizzare

stdext::hash_map my_map<MyClass, MyValue, MyClass_Hasher> 
+0

Penso che l'operatore() s dovrebbe essere la funzione 'const' o MSVC2005 genererà l'errore c3849 – avee