mercredi 23 octobre 2019

Sorting an array of vectors in decreasing order while using a comparator (C++)

I have a vector of Car* objects in them that point to an object that has an id and position attribute. I want to sort the vector in decreasing order by position (i.e., the highest position at vector[0] etc.).

Here is the sorting and comparator code below:

bool comparator(Car* firstObject, Car* secondObject) {
    return firstObject->get_position() > secondObject->get_position();
}

void sortingFunction(vector<Car*> arrayOfCars) {
    sort(arrayOfCars->begin(), arrayofCars->end(), comparator);
}

I tried to use the std::reverse() method, but (and I could be wrong) I saw it only really works with numberical vectors rather than object vectors. Would enumeration be a way to use the reverse method or is there a way for me to somehow add the greater functionality to the sort function with the comparator?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire