views:

420

answers:

1

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?

+19  A: 

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());
Evan Teran
Ahh, you beat me to it...
Andreas Magnusson
+1 And me as well hehe :)
Magnus Skog
I am getting an error: C2804: binary 'operator <' has too many parameters (referring to the line starting with: "bool operator<(const").
Brock Woolf
It's got to be an operator() instead of an operator<
sth
Aaah, it should be operator(). It's a functor.
Magnus Skog
I tried to figure it out, but you guys beat me to it :) Thanks it works!
Brock Woolf
@Adam Rosenfield: thanks for the edit, i was a bit too eager to get the answer out fast ;).
Evan Teran