简体   繁体   中英

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)

what might have I done wrong? I value your kind comments. Thank you

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 .

Your set thus can not contain more than one LaneConnectior with the same 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. So, GetLaneFrom()->GetLaneID() yields the same result on all LaneConnectors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM