문제

I want to use data structure that serves like .Net HashSet, I tried to use unordered_set with the default hashing method and custom comparer as follows:

struct comparer
    {
        bool operator()( const TCHAR* first,const TCHAR* second) const
        {   
            return _tcscmp((TCHAR*)first,(TCHAR*)second) == 0;
        }
    };

    typedef unordered_set<const TCHAR*,hash<const TCHAR*>,comparer> HashSet;

the problem is when I tried to use the HashtSet to find specific key (using find method) that is I just added using insert it returns HashSet::end()!!

Could you explain what is the problem? I'm using VC++ under VS2010

도움이 되었습니까?

해결책

Assuming that hash here is std::hash, there is no specialization of std::hash for char* or wchar* other than the generic specialization for any pointer type, that hashes based on the pointer value.

So, if you want to use TCHAR* as a hash key, with the hash based on the string contents instead of the pointer value, you'll need to supply a different hash functor class.

There are specializations of std::hash for string and wstring, that I think you could use if you pick the right one according to _UNICODE. I say "I think" because TCHAR* should just convert to string or wstring, but if I've missed something then you could write a simple wrapper.

If you were going to do either of those, though, then you could just as well use string or wstring as the hash key, since everything will need to be converted for hashing anyway. This will also allow you to add strings to your unordered_set without having to keep them hanging around until they're removed. With your code above, I imagine it's a nuisance adding anything other than string literals to the set.

If you're worried about speed, and not worried about managing the strings, then pick your favourite string hashing algorithm and apply it to the string data.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top