c++ - STL Sort use of Static Function -


i trying make enemies in game sorted in vector in order of distance player , using sort function. obviously, enemies objects basic predicate isn't enough , have make own function, did.

however, these functions have static, , so, how, in function, can compare distance between enemy , 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 code i'm trying use, static function (defined static in header) doesn't have access member variables , following doesn't work:

bool world::sortxdistance(entity *i, entity *j) {  return (getplayerdistance(i) < getplayerdistance(j));  } 

(also defined static in header) use stl sorting vector.

i have tried googling around, perhps don't recognise true problem, appreciated, or alternate way of doing considered. thank in advance :)

use functor reference world object member, 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, 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); 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -