【问题标题】:std map find is always truestd map find 始终为真
【发布时间】:2016-02-12 07:24:07
【问题描述】:

我在使用 std::map 时遇到问题,尤其是在使用 find 时。 我有以下代码。

class MyClass
{
    update(const QVariant&);
    QVariant m_itemInfo;
    std::map<QVariant, int> m_testMap;
}

void update(const QVariant& itemInfo)
{
    if(m_itemInfo != itemInfo)
    {
         // The items are not equal
         m_itemInfo = itemInfo;
    }
    if(m_testMap.find(itemInfo) == m_testMap.end())
    {
        // TestMap doesnt contain key itemInfo.
        m_testMap.insert(std::make_pair(itemInfo, 1));
    }

    // More code
}

函数update 在我的代码中被多次调用(使用不同的 itemInfo 对象)。现在当我开始调试它时,我看到第一次调用update 时,第一个和第二个 if 循环都进入了。到现在为止还挺好。但是第二次调用update 我确实看到调用了第一个 if 循环,但第二个被跳过了!我在这里错过了什么?

【问题讨论】:

  • 显示你的 QVariant 的 operator==,你也可以稍微编辑一下来制作一个 MCVE [stackoverflow.com/help/mcve]。
  • if(m_testMap.find(itemInfo) == m_testMap.end()) 的成功/失败取决于QVariant::operator&lt; 的行为。如果没有看到Minimal, Complete, and Verifiable example,就很难说出哪里出了问题。
  • 所以它依赖于 operator
  • @Frank 默认情况下,std::map 考虑两个元素ab,当且仅当!(a &lt; b)!(b &lt; a) 相等。如果您的QVariants 无法比较,那么它们在std::map 眼中可能是相等的,您需要std::unordered_mapQHash 或自定义比较器。

标签: c++ qt stl find stdmap


【解决方案1】:

我猜问题是您传递给 Update 方法的第一个和第二个 QVariants 具有不同的类型(例如,booluint)。 std::map::find 不使用 !=operator 来比较键,它默认使用 operator QVariant 值具有不同的类型,则运算符 != 和 std::map::find 按以下方式比较键:

如果容器的比较对象反射性地返回 false(即,无论元素作为参数传递的顺序如何),则认为两个键是等效的。

std::map::find 认为 v1 等于 v2

    if(!(v1<v2) && !(v2>v1)) { //is TRUE !!!
    }

要解决您的问题,您应该为std:map 定义一个less 比较。

    class QVariantLessCompare {
        bool operator()(const QVariant&  v1, QVariant& v2) const {
           // ==== You SHOULD IMPLEMENT appropriate comparison here!!! ====
           // Implementation will depend on type of QVariant values you use 
           //return v1 < v2;
       }
    };

并以这样的方式使用QVariantCompare

    std::map<QVariant, int, QVariantLessCompare> m_testMap; 

【讨论】:

    【解决方案2】:

    更典型的解决方案是使用QMap,它正确地实现了大多数QVariant 类型的比较。它不会开箱即用userTypes(),但这仍然可能适合您的应用程序。

    Володин Андрей 提出的解决方案的更简洁版本,其构建可能如下所示:

    struct QVariantLessCompare {
        bool operator()(const QVariant& v1,const QVariant& v2) const 
        {
            return v1.toInt() < v2.toInt();
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2012-02-05
      • 1970-01-01
      • 2022-08-24
      • 2016-04-10
      相关资源
      最近更新 更多