【问题标题】:How to use struct as key in std::map如何在 std::map 中使用 struct 作为键
【发布时间】:2011-07-18 05:16:12
【问题描述】:

我想使用一个std::map,它的键和值元素都是结构。

我收到以下错误: error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const GUID

我知道在这种情况下我应该重载operator <,但问题是我无法访问我想要使用的结构的代码(VC++ 中的GUID 结构)。

这里是sn-p的代码:

//.h

#include <map>
using namespace std;

map<GUID,GUID> mapGUID;


//.cpp

GUID tempObj1, tempObj2;              
mapGUID.insert( pair<GUID,GUID>(tempObj1, tempObj2) );   

如何解决这个问题?

【问题讨论】:

    标签: c++ stl visual-studio-2005 stdmap


    【解决方案1】:

    GUIDS 没有运算符

    【讨论】:

      【解决方案2】:

      可能使用从 GUID 继承的类,您在其中实现运算符

      【讨论】:

        【解决方案3】:

        您可以将比较运算符定义为独立函数:

        bool operator<(const GUID & Left, const GUID & Right)
        {
            // comparison logic goes here
        }
        

        或者,由于通常 std::map 模板的第三个参数:

        struct GUIDComparer
        {
            bool operator()(const GUID & Left, const GUID & Right) const
            {
                // comparison logic goes here
            }
        };
        
        // ...
        
        std::map<GUID, GUID, GUIDComparer> mapGUID;
        

        【讨论】:

        • 当我按照你所说的方式编写时,我得到了错误,因为operator&lt; 函数应该看起来像bool operator&lt;(GUID&amp; left, GUID&amp; right);即使在这之后我得到编译器error C2804: binary 'operator &lt;' has too many parameters。我不明白为什么,因为这个函数没有放在我的包含地图的类中?
        • @kobac -- 我认为@Matteo 的意思是bool operator()(const std::pair&lt;GUID, GUID&gt; &amp; Left, const std::pair&lt;GUID, GUID&gt; &amp; Right)
        • 正确答案是bool operator()(const GUID &amp;left, const GUID &amp;right) const
        • Ops,第二个我有点搞砸了;抱歉,现在应该修复了。 :S
        • 仍然需要operator()。请更正它,以便寻找相同问题的人有一个完整的解决方案。 Grazie Matteo。
        【解决方案4】:

        您用作键的任何类型都必须提供严格的弱排序。您可以提供一个比较器类型作为第三个模板参数,也可以为您的类型重载 operator&lt;

        【讨论】:

        • 赞成指定 严格的弱排序。这很重要,否则天真地尝试实现我们自己的operator&lt; 可能不会足够严格地订购。我的没有,直到我在别处学到了这个词。
        猜你喜欢
        • 2020-07-07
        • 1970-01-01
        • 2012-10-04
        • 2011-11-04
        • 1970-01-01
        • 2014-08-06
        • 2011-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多