如何解决如何使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。