使用多个键实现类似QHash的查找 [英] Implementing a QHash-like lookup with multiple keys
问题描述
我正在尝试找到实现类似QHash的查找表的最佳方法,该查找表使用多个键返回一个值.我已经读过Boost库具有类似的功能,但我想尽可能避免这种情况.
I'm trying to find the best way to implement a QHash-like lookup table that uses multiple keys to return one value. I have read that the Boost library has similar functionality, but I would like to avoid this if possible.
我想做的一个例子如下(显然,下面的伪代码是不可能的):
An example of what I would like to do is as follows (obviously the following pseudo-code is not possible):
//First key (int) - Engine cylinders
//Second key (int) - Car weight
//Value (int) - Top speed
MyLookup<int, int, int> m_Lookup
m_Lookup.insert(6, 1000, 210);
m_Lookup.insert(6, 1500, 190);
m_Lookup.value(6, 1000); //Returns 210
我的第一个想法(也是非常慢的想法)是创建一个Struct,然后遍历一个列表,直到找到一个合格的项目为止.
My first (and extremely slow) idea was to just create a Struct, and iterate over a list until I find a qualifying item.
Struct Vehicle {
int cyl;
int weight;
int speed'
}
QList<Vehicle> carList; //Assume this is populated
for(i = 0; i < carList.length; ++i) {
if(carList[i].cyl == 6 && carList[i].weight == 1000) {
return carList[i].speed; } }
我的另一个想法是将两个键连接成一个键,并实现一对函数以在需要时组合和分离两个键.尽管这可以奏效,并且可能比完整的迭代要快得多,但似乎有些不合时宜.
My other idea was to concatenate the two keys into one key, and implement a couple functions to combine and separate the two keys when needed. While this would work, and probably be a lot faster than a full iteration, it seems a bit hacked together.
QHash<QString, int> m_Lookup;
m_Lookup.insert("6|1000", 210);
有人知道更好的方法来实现这一目标吗?
Does anyone know of a better way to try and achieve this?
推荐答案
选项1
使用QPair
作为密钥:
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)));
选项2
创建一个类来表示所需的车辆特性(用相等/不相等运算符完成),并为您的类创建qHash
的实现:
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;
}
这篇关于使用多个键实现类似QHash的查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!