How to use struct as key in std::map

[亡魂溺海] 提交于 2019-12-05 08:15:43
Matteo Italia

You can define the comparison operator as a freestanding function:

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

Or, since in general a < operator does not make much sense for GUIDs, you could instead provide a custom comparison functor as the third argument of the std::map template:

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

// ...

std::map<GUID, GUID, GUIDComparer> mapGUID;

Any type you use as a key has to provide a strict weak ordering. You can supply a comparator type as a third template argument, or you can overload operator< for your type.

There is no operator < for GUIDS so you either have to provide the comparison operator or use a different key.

May be using class inherited from GUID in which you implement operator < would be a workaround for you?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!