Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Using Qt Datatypes in Standard Library Unordered Containers

// OK, uses std::hash<int>, which is provided by the Standard Library
std::unordered_set<int> int_set;

// OK, uses std::hash<QString>, which is provided by Qt
std::unordered_set<QString> string_set;

// ERROR: std::hash<QDateTime> does not exist
std::unordered_set<QDateTime> date_set;
struct QDateTimeHasher {
  size_t operator()(const QDateTime &dt) const noexcept {
     // ... calculate the hash ...
  }
};

// Uses QDateTimeHasher as the hashing function for this map
std::unordered_map<QDateTime, Event, QDateTimeHasher> date_to_event_map;
struct QDateTimeHasher {
  size_t operator()(const QDateTime &dt) const noexcept {
     return qHash(dt);
  }
};

struct QPointHasher {
  size_t operator()(const QPoint &dt) const noexcept {
     return qHash(dt);
  }
};

// ... repeat for any other Qt datatype ...
std::unordered_map<QDateTime,
                   Event,
                   KDToolBox::QtHasher<QDateTime>> map;

About KDAB


GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer

Learn Modern C++

Learn more