使用operator()对std :: set排序以对插入进行排序 [英] sort std::set using operator() to order the insertions

查看:211
本文介绍了使用operator()对std :: set排序以对插入进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> 之后,我将继续发布该帖子> 我们有一个类:

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隐式成为 .由于如果ab具有相同的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不能包含多个具有相同LaneIDLaneConnectior.

Your set thus can not contain more than one LaneConnectior with the same LaneID.

这篇关于使用operator()对std :: set排序以对插入进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆