Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort QVector of pointers to custom objects

My Question:

What is the best way to assign numbers to each Camera in a QVector<Camera*> where the following specifications should apply:

  • The unsorted QVector should keep its order
  • The int number of each Camera should be assigned depending on its QString macAddress
  • The int number should start with 0 for the "lowest" macAddress (QString::operator<)

Sources:

class Camera {
    int number;
    QString macAddress;
}

Current solution:

My curent solution is to:

  • Implement Camera::operator<

    bool Camera::operator<(const Camera &cam) const {
        return(this->macAddress < cam.macAddress);
    }
    
  • Implement a compare struct

    struct CameraCompare {
        bool operator()(const Camera *a, const Camera *b) {
            return(*a < *b);
        }
    }
    
  • Create a temporary QVector of pointers to the same Camera-objects and then using std::sort on the temporary vector and assigning the numbers like the following:

    QVector<Camera*> tempVector;
    for(quint8 i = 0; i < cameras->size(); i++) {
        Camera *temp = (*cameras)[i];
        tempVector.append(temp);
    }
    std::sort(tempVector.begin(), tempVector.end(), CameraCompare());
    for(quint8 i = 0; i < tempVector.size(); i++) {
        tempVector[i]->setNumber(i); // Edited
    }
    

Edit: My question now is: Is there a better way to accomplish this?

like image 525
chrizbee Avatar asked Nov 17 '25 04:11

chrizbee


1 Answers

There's nothing wrong with your solution. It sorts the vector fine. But it seems there's something wrong here:

for(quint8 i = 0; i < tempVector.size(); i++) {
    cameras->at(i)->setNumber(i);
}

This code sets the number of each camera, the index of it in the original vector NOT the sorted vector. I think it should be replaced with:

for(quint8 i = 0; i < tempVector.size(); i++) {
    int number = tempVector.indexOf(cameras.at(i));
    cameras->at(i)->setNumber(number);
}
like image 62
frogatto Avatar answered Nov 18 '25 19:11

frogatto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!