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 eachCamera
should be assigned depending on itsQString macAddress
- The
int number
should start with0
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?