rahman
rahman

Reputation: 4948

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

Upvotes: 0

Views: 137

Answers (2)

Hindol
Hindol

Reputation: 2990

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.

Upvotes: 1

blinnov.com
blinnov.com

Reputation: 305

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

Upvotes: 0

Related Questions