【发布时间】:2020-08-28 12:12:03
【问题描述】:
我有以下代码,我遇到了一些错误,例如:
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" );
【问题讨论】:
-
“一些错误”不是很有帮助。你遇到了什么错误?
-
要将
struct用作键,需要有一个比较运算符<。 -
我正要写一个答案。我得到了this。也许这足以让你继续前进。
-
@TedLyngmo。谢谢,这就是我的意思。顺便说一句,我想通了。
-
@MarcellJuhasz 太棒了!快乐黑客! :-) 你推荐使用
std::tie作为operator<中的逻辑。它使得它很多更容易阅读和维护。在创建符合地图要求的严格弱排序的运算符时也很容易出错。
标签: c++ c++11 struct key stdmap