3

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?

chrizbee
  • 145
  • 1
  • 13
  • I am not sure what the best way is. But the reason why your numbering doesn't work could be because of the last line "cameras->at(i)->setNumber(i);" I think it should be "tempVector[i]->setNumber(i);" And since you are working with pointer it should update the correct camera object in cameras – sajas Dec 27 '17 at 09:46
  • One approach would be to implement an adapter iterator that would wrap the camera numbers but and return a wrapper type convertible to int that wraps a pointer to element, but comparing the mac addresses. – Kuba hasn't forgotten Monica Dec 27 '17 at 19:00

1 Answers1

1

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);
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Yes it did. But isn't this tempVector a quite ugly solution tho? Do you have any ideas on how to solve the problem any better? – chrizbee Dec 27 '17 at 10:37
  • 2
    @ChristianB You can use `QMap`. It's automatically sorted based on its keys. If you consider `macAddress` as the key of each camera, you can simply use this container. – frogatto Dec 27 '17 at 10:42
  • Thanks, I didn't think of that yet! – chrizbee Dec 27 '17 at 10:51