unordered_map哈希函数和运算符==

时间:2016-08-24 19:55:09

标签: stl unordered-map

我创建了一个unordered_map,其中class作为键并重载了散列函数。当我使用unordered_map :: find函数时,它不会进入相等函数(operator ==)而是使用散列函数来查找传递给unordered_map :: find的键的相应值。每次调用“==”运算符时我都会尝试打印,我注意到既不计数也不使用“==”,而是使用散列函数。

我在这里缺少什么? 我想要做的是定义一个包含unordered_map和单个值的键。如果单个值在unordered_map中,则认为两个键相等;

这样的事情:

struct key_t{
    int single_val;
    unordered_map multi_val;
}

bool operator==(const key_t& src1, const key_t& src2) {
   return (src1.multi_val.count(src2.single_val) != 0);
}

这就是我所做的:

unordered_map<fixed_attribute_t, vector<unsigned int>, fixed_attribute_t::hash_t> fixedAttributeMap;

我定义了一个==运算符如下:

bool operator==(const fixed_attribute_t& fixedAttribute1, const fixed_attribute_t& fixedAttribute2) {
// case: multiple ports

if (fixedAttribute2.index != fixedAttribute1.index) {
    return false;
}

if (fixedAttribute1.portsMap != NULL) {
    return (fixedAttribute1.portsMap->count(fixedAttribute2.value) != 0);
}

if (fixedAttribute1.portRangeEnd != -1) {
    return ((fixedAttribute2.value <= fixedAttribute1.portRangeEnd && fixedAttribute2.value >= fixedAttribute1.portRangeStart
            && fixedAttribute1.isPortAttr == true));
}
return (fixedAttribute1.value == fixedAttribute2.value);

}

哈希函数实现:

class hash_t {
    std::hash<int> stdHash;

public:

    size_t operator()(const fixed_attribute_t& fixedAttribute) const {
        int portNum;
        if (fixedAttribute.portsMap != NULL) {
            auto it = fixedAttribute.portsMap->begin();
            portNum = it->first;
        }
        return stdHash(fixedAttribute.value ^ portNum);
    }
};

非常感谢!

0 个答案:

没有答案
相关问题