Hello I'm creating a game engine. In order to draw everything correctly I need to sort a vector (vector<game_object*>) by each contents z value

I miserably failed to do it with std's sort() so Id like to know what's the most efficient way I could sort this vector [If its efficient , its likely complex so please post quite a bit of example code :icon_cheesygrin: ]

Recommended Answers

All 5 Replies

Use binary predicate :

template<typename Object>
struct PointerComp{
 bool operator()(const Object* lhs, const Object* rhs)const{
  return *lhs < *rhs;
 }
};
//....
std::vector<game_object*> objects;
//...
std::sort(objects.begin(),object.end(),PointerComp<game_object>());

how dose it sort the z valuse ... Should I add it so the code looks like this ?

template<typename Object>
struct PointerComp{
 bool operator()(const Object* lhs, const Object* rhs)const{
  return *lhs->z < *rhs->z;
 }
};
//....
std::vector<game_object*> objects;
//...
std::sort(objects.begin(),object.end(),PointerComp<game_object>());

If yor wan't to sort it based on its z-values then use this predicate:

template<typename Object>
struct PointerComp{
 bool operator()(const Object* lhs, const Object* rhs)const{
  return lhs->getZ() < rhs->getZ();
}
};
template<typename Object>

struct PointerComp
{
    bool operator()(const Object* lhs, const Object* rhs)const
    {
        return *lhs->z < *rhs->z;
    }
};


// update objects

void update(SDL_Surface * screen)
{
    std::sort(var::_objects_.begin(),var::_objects_.end(),PointerComp<game_object>()); // error

            ### error: invalid type argument of ‘unary *’ ###

what am I doing wrong here ?

nvm I fixed it , Thanks firstperson !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.