简体   繁体   中英

STL Sort use of Static Function

I am trying to make it so that my enemies in my game are sorted in a vector in order of distance from the player and so I am using the sort function. Obviously, my enemies are objects so the basic predicate isn't enough and I have to make my own function, so I did.

However, these functions have to be static, and so, how, in this function, can I compare the distance between the enemy and the player?

double World::getPlayerDistance(Entity* enemy){

int xDistance = enemy->m_xValue - m_pPlayer->m_xValue;
int yDistance = enemy->m_yValue - m_pPlayer->m_yValue;

double dist = sqrt(pow((double)xDistance, 2) + pow((double)yDistance, 2));

return dist;
}

This is the code I'm trying to use, but as it is a static function (defined static in the header) it doesn't have access to member variables and so the following doesn't work:

bool World::sortXDistance(Entity *i, Entity *j) { 
return (getPlayerDistance(i) < getPlayerDistance(j)); 
}

(Also defined static in header) This is for use with the STL sorting with a Vector.

I have tried googling around, but perhps I don't even recognise the true problem, so any help would be appreciated, or an alternate way of doing it would be considered. Thank you in advance :)

Use a functor with a reference to a World object as a member, like this one:

struct CloserToPlayer
{
    World const & world_;
    CloserToPlayer(World const & world) :world_(world) {}

    bool operator()(Entity const * lhs, Entity const * rhs) const
    {
        return world_.getPlayerDistance(lhs) < world_.getPlayerDistance(rhs);
    }
};

...
World theWorld;
std::vector<Entity*> entities;
...
std::sort(entities.begin(), entities.end(), CloserToPlayer(theWorld));

Or, with C++11 lambdas:

auto CloserToPlayer = [&](Entity const * lhs, Entity const * rhs) {
        return theWorld.getPlayerDistance(lhs) < theWorld.getPlayerDistance(rhs);
    };
std::sort(entities.begin(), entities.end(), CloserToPlayer);

I fixed my own problem. Instead of trying to access a non-static member function inside a static function, I did the player distance check outside of this, and assigned the result to the entities/enemies. This way, when I call sortXDistance, I just did:

bool World::sortXDistance(Entity *i, Entity *j){
    return (i->m_playerDistance < j->m_playerDistance);
}

Thank for your help, I did try your ways out but just kept getting errors I didn't understand :) My way is here at least for reference if anyone ever has this problem and wants my terrible way, and I'll give you the answer for the most likely better way of doing it.

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