QMap :: contains()和QMap :: value()找不到现有的键值对

我正在将Qt 4.7.4与MS Visual C ++ 2010一起使用。

我正在使用以下QMap:

QMap<T_FileMapKey, HANDLE>  m_oMapHistHandle; 

其中T_FileMapKey定义为:

typedef struct tagT_FileMapKey
{
    int iSubscriptIdx;
    int iFilterIdx_1;
    int iFilterIdx_2;
} T_FileMapKey;

为了使整个过程顺利进行,我重载了<运算符:

bool operator< (const T_FileMapKey& tVal1, const T_FileMapKey& tVal2)
{
    if(tVal1.iSubscriptIdx < tVal2.iSubscriptIdx)
    {
        return true;
    }
    else
    {
        if(tVal1.iFilterIdx_1 < tVal2.iFilterIdx_1)
        {
            return true;
        }
        else
        {
            if (tVal1.iFilterIdx_2 < tVal2.iFilterIdx_2)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}; 

如您所预料的那样,整个操作是将文件句柄以3维数组的顺序存储。我使用的是QMap,因为仅使用了索引的一些组合,它们可能是大数目。

我的问题是:

if (INVALID_HANDLE_VALUE == m_oMapCurrHandle.value(tFileKey, fdInvalidHandle))
....

if (false == m_oMapHistHandle.contains(tFileKey))
....

(其中tFileKey是T_FileMapKey变量)并不总是返回正确的值。

在正常情况下,QMap会随着时间增长,这意味着如果遇到新的索引组合,则会打开一个文件,并将该条目添加到QMap中。如果以调试模式启动该应用程序,则Qt Visual Studio加载项允许我窥视存储的键值对。我可以看到调试监视中存在该条目(例如{0,32767,0}),但是两个函数调用(包含和值)告诉我QMap没有存储此类键。通常,在QMap具有至少15个键/值对之后,会遇到此行为。

这可能是Qt 4.7.4中的错误吗?怎么了?

巴里

operator<错了 解释一下,让我们考虑一个operator<为just编写代码的更简单的原因pair<int, int>您的版本已实现:

bool operator<(const pair<int, int>& lhs, const pair<int, int>& rhs) 
{
    if (lhs.first < rhs.first) {
        return true; // (1)
    }
    else if (lhs.second < rhs.second) {
        return true; // (2)
    }
    else {
        return false; // (3)
    }
}

因此{1,4}<{2,3}因为(1)。但是{2,3}<{1,4}因为(2)!因此,我们最终得到一个operator<未建立排序的。

建立词典比较的最简单方法是依次完全处理每个术语:

bool operator<(const pair<int, int>& lhs, const pair<int, int>& rhs)
{
    if (lhs.first != rhs.first) {
        return lhs.first < rhs.first;
    }
    else {
        return lhs.second < rhs.second;
    }
}

同样的想法可以很容易地扩展到您的三元组。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章