[英]sort std::set using operator() to order the insertions
I am continuing this post after This we have a class as: 我将在此课程之后继续该帖子。
class LaneConnector {
public:
const Lane* getLaneFrom() const {
return From;
}
const Lane* getLaneTo() const {
return To;
}
private:
Lane* From;
Lane* To;
}
and a functor to compare as: 和一个仿函数作比较:
struct MyLaneConectorSorter {
bool operator() (const LaneConnector* rhs, const LaneConnector* lhs) const
{
// you may want to put some null pointer checks in here
const Lane* a = lhs->getLaneFrom();
const Lane* b = rhs->getLaneFrom();
return a->getLaneID() < b->getLaneID();
}
};
and finally a source and destination set: 最后是源和目标集:
const std::set<LaneConnector*> src = ..... ;
const std::set<LaneConnector*, MyLaneConectorSorter> dest(src.begin(), src.end(), MyLaneConectorSorter());
The size of the dest set will be 1 while the src has more(14 in my case) 目标集的大小将为1,而src则为更多(本例中为14)
what might have I done wrong? 我可能做错了什么? I value your kind comments.
我重视您的评论。 Thank you
谢谢
std::set
keeps track of elements based on the key . std::set
根据key跟踪元素。 In your comparator you have return a->getLaneID() < b->getLaneID();
在比较器中,您将
return a->getLaneID() < b->getLaneID();
. 。 Thus
Lane ID
implicitly becomes the key . 因此,
Lane ID
隐式成为关键 。 Since if a
and b
have the same LaneID
, then both MyLaneConectorSorter(a, b)
and MyLaneConectorSorter(b, a)
are returning false
. 由于如果
a
和b
具有相同的LaneID
,则MyLaneConectorSorter(a, b)
和 MyLaneConectorSorter(b, a)
都将返回false
。
Your set
thus can not contain more than one LaneConnectior
with the same LaneID
. 你的
set
,因此不能包含多个LaneConnectior
具有相同LaneID
。
There is a very simple way to catch problems like this way before they get a chance to expose themselves. 有一种非常简单的方法可以在问题有机会暴露出来之前捕获此类问题。 Write unit tests!
编写单元测试!
My guess is that all your LaneConnectors start at the same line. 我的猜测是您所有的LaneConnectors都从同一行开始。 So, GetLaneFrom()->GetLaneID() yields the same result on all LaneConnectors
因此,GetLaneFrom()-> GetLaneID()在所有LaneConnectors上产生相同的结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.