Implementing a QHash-like lookup with multiple keys

落爺英雄遲暮 提交于 2019-12-05 21:28:09

Option 1

Use a QPair as your key:

QHash<QPair<int, int>, int> m_Lookup;

m_Lookup.insert(QPair<int, int>(6, 1000), 210);
m_Lookup.insert(QPair<int, int>(6, 1500), 190);

qDebug("Value is %d", m_Lookup.value(QPair<int, int>(6, 1000)));

Option 2

Create a class to represent your desired vehicle characteristics (complete with equality/inequality operators) and create an implementation of qHash for your class:

class Vehicle
{
public:
   Vehicle(short cylinders, short weight) 
      : m_Cylinders(cylinders), m_Weight(weight) { }

   short cylinders() const { return m_Cylinders; }
   short weight() const { return m_Weight; }

   bool operator==(const Vehicle& other) const 
      { return (m_Cylinders == other.m_Cylinders && m_Weight == other.m_Weight); }
   bool operator!=(const Vehicle& other) const 
      { return !operator==(other); }

private:
   short m_Cylinders;
   short m_Weight;
};

inline uint qHash(const Vehicle& key)
{
   uint k = static_cast<uint>(key.cylinders()) << 16 | static_cast<uint>(key.weight());
   return k;
}

int main(int argc, char** argv)
{
   QHash<Vehicle, int> m_Lookup;

   m_Lookup.insert(Vehicle(6, 1000), 210);
   m_Lookup.insert(Vehicle(6, 1500), 190);

   qDebug("Value is %d", m_Lookup.value(Vehicle(6, 1000)));

   return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!