Portable Hash Map



  • Ich möchte in meinem Code eine hash_map benutzen. Also eine im SGI STL Style, wie sie auf den meisten Compilern existiert. Ich habe also einen kleinen Header geschrieben:

    #ifdef __GNUC__
    #define HH_HASH_MAP <ext/hash_map>
    #define HH_HASHD __gnu_cxx
    #endif
    
    #include HH_HASH_MAP
    #include <string>
    #include <typeinfo>
    
    namespace hashd = HH_HASHD;
    
    namespace HH_HASHD {
    template<class Ch, class ChTr, class A> struct hash<std::basic_string<Ch, ChTr, A> > {
    	typedef std::basic_string<Ch, ChTr, A> string_t;
    
    	std::size_t operator() (string_t const &a) const {
    		size_t x = 0;
    		for (typename string_t::const_iterator it = a.begin(); it != a.end(); ++it)
    			x = 5*x + *it;
    		return x;
    	}
    };
    }
    

    Wie man sieht ist der Code nur für GCC ausgelegt. Ich würde mich freuen, wenn Nutzer von Nicht-GCC-Compilern den Code anpassen würden (mittels den beiden Defines oben soweit möglich) - bzw. natürlich mir sagen, in welchem Header und Namespace die hash_map bei eben diesen ist.

    Danke im Voraus
    MrN

    PS: Der Code ist Public Domain 🤡


  • Mod

    die headerdatei befindet sich bei vc im standard includeverzeichnis; hash_map ist im namespace stdext.



  • So jetzt auch für MSVC.. hab leider keinen solchen zum Testen da, also ungetestet 😃

    #ifdef __GNUC__
    #define HH_HASH_MAP <ext/hash_map>
    #define HH_HASHD __gnu_cxx
    #define NEED_HASH_FOR_STRING
    #else
    #define HH_HASH_MAP <hash_map>
    #endif
    
    #ifdef _MSC_VER
    #define HH_HASHD stdext
    #define _DEFINE_DEPRECATED_HASH_CLASSES 0
    #endif
    
    #include HH_HASH_MAP
    #include <string>
    
    namespace hashd = HH_HASHD;
    
    #ifdef  NEED_HASH_FOR_STRING
    namespace HH_HASHD {
    template<class Ch, class ChTr, class A> struct hash<std::basic_string<Ch, ChTr, A> > {
    	typedef std::basic_string<Ch, ChTr, A> string_t;
    
    	std::size_t operator() (string_t const &a) const {
    		size_t x = 0;
    		for (typename string_t::const_iterator it = a.begin(); it != a.end(); ++it)
    			x = 5*x + *it;
    		return x;
    	}
    };
    }
    #endif
    

    EDIT: weniger ein Unterstrich, danke cd9000
    EDIT: jetzt keine hash-Spezialisierung für string für den msvc mehr
    EDIT: keine warnungen mehr (hoffentlich)


Anmelden zum Antworten