【问题标题】:C++ map with custom key带有自定义键的 C++ 映射
【发布时间】:2020-07-03 18:02:56
【问题描述】:

我有 C++ 映射的自定义键,“

class CustomKey;

typedef map<CustomKey, int>     KeyValueMap;

class CustomKey {
    public:
    string      key1;
    int         key2;
    int         key3;

    bool operator < (const CustomKey & rhs) const {
        return ((key1 < rhs.key1)
             || ((key1 == rhs.key1) && (key2 < rhs.key2))
             || ((key2 == rhs.key2) && (key3 < rhs.key3)));
    }

    void display() const {
        cout << key1 << ":" << key2 <<":" << key3;
    }
};

我可以添加并显示下面的所有五个键。

void addDataToMap(KeyValueMap & valueMap)   {
    CustomKey   key1 = {"one", 100, 50};
    valueMap[key1] = 1;

    CustomKey   key2 = {"two", 200, 150};
    valueMap[key2] = 2;

    CustomKey   key3 = {"moreabc", 100, 100};
    valueMap[key3] = 27;

    CustomKey   key4 = {"less", 100, 150};
    valueMap[key4] = 30;

    CustomKey   key5 = {"morexyz", 100, 101};
    valueMap[key5] = 33;
}

void displayMap(const KeyValueMap & valueMap)   {
    KeyValueMap::const_iterator iter = valueMap.begin();
    while(iter != valueMap.end())   {
        iter->first.display();
        cout << " => " << iter->second << endl;
        iter++;
    }
}

但奇怪的是,以下情况的搜索失败。 addDataToMap 中不同的加法组合有不同的结果。

void searchMap(const KeyValueMap & valueMap)    {
    CustomKey   key3 = {"morexyz", 100, 101};
    cout << "MapSize = " << valueMap.size() << endl;
    KeyValueMap::const_iterator iter = valueMap.find(key3);
    if(iter == valueMap.end())  {
        cout << "NotFound" << endl;
        return;
    }

    cout << iter->second << endl;
}

int main()  {
    KeyValueMap     valueMap;

    addDataToMap(valueMap);

    displayMap(valueMap);

    searchMap(valueMap);

    cout << endl;
    return 0;
}

输出:-

one:100:50 => 1
moreabc:100:100 => 27
morexyz:100:101 => 33
less:100:150 => 30
two:200:150 => 2
MapSize = 5
NotFound

在'

【问题讨论】:

  • 您的operator&lt; 没有给出严格的弱排序。

标签: c++ class dictionary stl operator-overloading


【解决方案1】:

使用操作符

#include <tuple>

//...

bool operator < (const CustomKey & rhs) const {
    return std::tie( key1, key2, key3 ) < std::tie( rhs.key1, rhs.key2, rhs.key3 );
}

这样的算子定义清晰,不易出错。

否则你的算子不满足提供严格弱序关系的要求。

【讨论】:

    【解决方案2】:

    尝试考虑key1 &gt; rhs.key1key2 == rhs.key2key3 &lt; rhs.key3 的情况,operator &lt; 将返回true,这是意料之外的。

    您可以将(key1 == rhs.key1) 保留在operator &lt;operator || 的最后一个分支中。例如

    bool operator < (const CustomKey & rhs) const {
        return ((key1 < rhs.key1) || 
                ((key1 == rhs.key1) && (key2 < rhs.key2)) || 
                ((key1 == rhs.key1) && (key2 == rhs.key2) && (key3 < rhs.key3)));
    }
    

    LIVE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多