使用operator()对std :: set排序以对插入进行排序 [英] 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();
}
};
最后是源和目标集:
const std::set<LaneConnector*> src = ..... ;
const std::set<LaneConnector*, MyLaneConectorSorter> dest(src.begin(), src.end(), MyLaneConectorSorter());
目标集的大小将为1,而src会更大(在我的情况下为14)
The size of the dest set will be 1 while the src has more(14 in my case)
我可能做错了什么?我很重视您的评论.谢谢
what might have I done wrong? I value your kind comments. Thank you
推荐答案
std::set
根据 键 跟踪元素.在您的比较器中,您有return a->getLaneID() < b->getLaneID();
.因此,Lane ID
隐式成为 键 .由于如果a
和b
具有相同的LaneID
,则MyLaneConectorSorter(a, b)
和 MyLaneConectorSorter(b, a)
都将返回false
.
std::set
keeps track of elements based on the key. In your comparator you have return a->getLaneID() < b->getLaneID();
. Thus Lane ID
implicitly becomes the key. Since if a
and b
have the same LaneID
, then both MyLaneConectorSorter(a, b)
and MyLaneConectorSorter(b, a)
are returning false
.
您的set
不能包含多个具有相同LaneID
的LaneConnectior
.
Your set
thus can not contain more than one LaneConnectior
with the same LaneID
.
这篇关于使用operator()对std :: set排序以对插入进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!