问题描述
我有以下代码,出现了一些错误,例如:
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