Using QString as a key in std :: unordered_map

I try to use QStringas key in std::unordered_map, however I get an error:

error C2280: 'std :: hash <_Kty> :: hash (const std :: hash <_Kty> &)': attempt to reference a remote function

I cannot switch to QHashbecause the type of the map value is not copied. Is there any way to make this work?

+4
source share
2 answers

The problem is the lack of specialization std::hash<QString>(). It's simple enough to define your own with good enough performance based on the dbj2 algorithm :

#include <QString>
#include <unordered_map>

namespace std
{
    template<> struct hash<QString>
    {
        std::size_t operator()(const QString& s) const noexcept
        {
            const QChar* str = s.data();
            std::size_t hash = 5381;

            for (int i = 0; i < s.size(); ++i)
                hash = ((hash << 5) + hash) + ((str->row() << 8) | (str++)->cell());

            return hash;
        }
    };
}

, , QString std::unordered_map, .

+6

hash , , .

, qHash:

#include <QString>
#include <functional>

namespace std {
  template<> struct hash<QString> {
    std::size_t operator()(const QString& s) const {
      return qHash(s);
    }
  };
}

std::size_t , unsigned int 64- , , , - . std::hash.

+1

Source: https://habr.com/ru/post/1692929/


All Articles