Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an object std::vector by its float value

Tags:

c++

stl

vector

I have a C++ std::vector denoted as:

std::vector<GameObject*> vectorToSort;

Each object in vectorToSort contains a float parameter which is returned by calling "DistanceFromCamera()":

vectorToSort.at(position)->DistanceFromCamera();

I wish to sort the vector by this float parameter however std::sort does not appear to be able to do this. How can I achieve this sort?

like image 299
Brock Woolf Avatar asked May 20 '09 21:05

Brock Woolf


1 Answers

you want to use a predicate like this:

struct VectorSortP {
    bool operator()(const GameObject *a, const GameObject *b) const {
        return a->DistanceFromCamera() < b->DistanceFromCamera();
    }
};

std::sort(vectorToSort.begin(), vectorToSort.end(), VectorSortP());
like image 185
Evan Teran Avatar answered Oct 21 '22 19:10

Evan Teran