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

2019-03-30 00:40发布

问题:

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?

回答1:

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());


标签: c++ stl vector