C ++ unordered_map哈希函数无法找到对象

时间:2016-11-11 08:25:38

标签: c++ object find unordered-map

我有一个类Scheduler,它包含两个对象的unordered_map。

class Scheduler
{
public:
...

private:
    unordered_map<Time, Activity> schedule;

}

我收到错误:&#39;列出迭代器而不是可解除引用的&#39; - 暗示在这里找不到对象:

void appoint(Time &time, const string activity) 
{
    Time hashTime(time + incrementor);
    schedule.find(hashTime)->second.active = 1; // <-- here
}

以下是我的哈希工具:

namespace std {
    // does get here
    template <>
    struct hash<Time>
    {
        std::size_t operator()(const Time& k) const
        {
            return ((hash<short>()(k.hr)
                ^ (hash<short>()(k.min) << 1)) >> 1)
                ^ (hash<bool>()(k.morning) << 1);
        }
    };
}


struct Time {
    short hr, min;
    bool morning;

    // doesnt get here
    bool operator==(const Time &other) const
    {
        return (hr == other.hr && min == other.min
                && morning == other.morning);
    }
}

以下证据表明它存在于unordered_map中。

unordered_map elements

我确认it == schedule.end()是真的。

        auto it = schedule.find(hashTime);
        if (it == schedule.end()) {
            cout << "ok";
        }


        // this does manage to get found
        schedule.insert(make_pair(Time(9, 30, 1), Activity(0,"")));
        auto it2 = schedule.find(hashTime);
        if (it2 == schedule.end()) {
            cout << "ok";
        }

不知何故,我对地图的初步构造不正确。

Scheduler() 
{
    Time start(12,0,1);             // 12:00am
    Time incrementor;               // 00:00
    Time static_incrementor(0, 15); // 00:15

    // creates an empty schedule
    // there are 96, 15 min intervals from 12:00am to 11:45pm
    for (int i = 0; i < 48; i++) {
        Time newTime(start + incrementor);
        newTime.morning = true;
        cout << newTime.hr << ":" << newTime.min << newTime.morning << endl;

        schedule.insert(make_pair(newTime, Activity(0, "")));
        incrementor += static_incrementor;
    }

    Time start2(12, 0, 0); // 12:00pm
    Time incrementor2;     // 00:00
    for (int i = 0; i < 48; i++) {
        Time newTime(start2 + incrementor2);
        newTime.morning = false;
        cout << newTime.hr << ":" << newTime.min << newTime.morning << endl;

        schedule.insert(make_pair(newTime, Activity(0, "")));
        incrementor2 += static_incrementor;
    }
};

1 个答案:

答案 0 :(得分:0)

我已经发现了这个问题 - 但是并没有完全理解它。这是因为现在每次插入都能确保独特的结构吗?也许有人可以评论。

schedule.insert(make_pair(Time(newTime.hr, newTime.min, newTime.morning), 
                        Activity(0, "")));