My Question:
What is the best way to assign numbers to each Camera in a QVector<Camera*> where the following specifications should apply:
QVector should keep its orderint number of each Camera should be assigned depending on its QString macAddressint 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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With