如何使用struct作为键?

问题描述

我有以下代码,出现了一些错误,例如:

struct duplicatedTurns
    {
        int nodeId;
        int min;
        int max;

        bool operator==(const duplicatedTurns& other) const
        {
            return nodeId == other.nodeId && min == other.min && max == other.max;
        }

I solved it here to following code:
bool operator<(const duplicatedTurns& other) const
{
if (nodeId != other.nodeId) return nodeId < other.nodeId;
if (min != other.min) return min < other.min;
if (max != other.max) return max < other.max;
return false;
}

    };

我要使用的容器:

std::map<duplicatedTurns,int> selected;

在我想在其中插入元素之后:

selected.insert(duplicatedturns{it->nodeId,std::min(it->toLinkId,it->fromLinkId),std::max(it->toLinkId,it->fromLinkId)},"here: increment the number if the key are the same" );

解决方法

如何在std :: map中使用struct作为键?

通过使用std::map的默认比较函数std::less使类小于可比类(可以通过为operator<定义满足指定要求的重载来实现) ,或通过提供自定义比较功能作为std::map的模板参数。

,

在C ++中,默认情况下对Map进行排序。这就是为什么必须定义operator

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...