• Advertisement
Sign in to follow this  

std::map and custom compare madness

This topic is 398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How on earth does the compare function in std::map works?

Even after searching i still havent figured it out.

 

I have one structure which have 4 pointer values needs to fully match when i want to equal the struct.

But std::map expects a < operator for comparing the struct - but i have no idea how this works - all examples i find are just comparing one thing - i have 4.

It seems that it is a sort comparator of some kind, but i cant get it work.

struct ArbiterKey {
    Body *bodyA;
    Body *bodyB;
    Shape *shapeA;
    Shape *shapeB;
    ArbiterKey(Body *bodyA, Body *bodyB, Shape *shapeA, Shape *shapeB) {
        if (bodyA < bodyB) {
            this->bodyA = bodyA;
            this->bodyB = bodyB;
        } else {
            this->bodyA = bodyB;
            this->bodyB = bodyA;
        }
        if (shapeA < shapeB) {
            this->shapeA = shapeA;
            this->shapeB = shapeB;
        } else {
            this->shapeA = shapeB;
            this->shapeB = shapeA;
        }
    }
};
bool operator < (const ArbiterKey& a1, const ArbiterKey& a2) {
    if (a1.bodyA < a2.bodyA)
        return true;
    if (a1.bodyA == a2.bodyA && a1.bodyB == a2.bodyB)
        return true;
    if (a1.shapeA < a2.shapeA)
        return true;
    if (a1.shapeA == a2.shapeA && a1.shapeB == a2.shapeB)
        return true;
    return false;
}

 

I simply want to compare the pointer addresses for all 4 fields thats it.

Share this post


Link to post
Share on other sites
Advertisement
Oh this was a pretty good explanation thanks!

Now it works:
 
bool operator < (const ArbiterKey& a1, const ArbiterKey& a2) {
	if (a1.bodyA < a2.bodyA) {
		return true;
	}
	if (a1.bodyA > a2.bodyA) {
		return false;
	}
	if (a1.bodyB < a2.bodyB) {
		return true;
	}
	if (a1.bodyB > a2.bodyB) {
		return false;
	}
	if (a1.shapeA < a2.shapeA) {
		return true;
	}
	if (a1.shapeA > a2.shapeA) {
		return false;
	}
	if (a1.shapeB < a2.shapeB) {
		return true;
	}
	if (a1.shapeB > a2.shapeB) {
		return false;
	}
	return false;
}
Edited by Finalspace

Share this post


Link to post
Share on other sites

Yep, I usually do it like below, it's a bit shorter.

bool operator < (const ArbiterKey& a1, const ArbiterKey& a2) {
    if (a1.bodyA != a2.bodyA)   return a1.bodyA < a2.bodyA;
    if (a1.bodyB !=  a2.bodyB)  return a1.bodyB < a2.bodyB; 
    if (a1.shapeA != a2.shapeA) return a1.shapeA < a2.shapeA;
    return a1.shapeB < a2.shapeB;
}

std::map actually sorts the elements in a tree, the iterator will give you increasing order.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement