I'm trying to sort a vector of objects so that objects with the same properties are right next to each other. Task is a class that takes and holds 3 pointers to some data somewhere.
vec.push_back(Task(&propertyOne, &propertyTwo, &propertyThree));
If I have a vector full of these, I want to sort them so that any Task that has equal propertyOne, propertyTwo, and propertyThree are put next to each other in the vector. If the two Task objects properties are not equal, it doesn't really matter where they go. Although it would be nice for them to go next to the Task objects that they have the most in common with.
How do I do this? I've tried the obvious (return a.propertyOne == b.propertyOne) but that didn't seem to work at all, and also it only compares the first property.
Best solution is use a tuple<property*, property*, property*> not a Task. This comes with comparison operators defined so you could simply do: vec.push_back(make_tuple(&propertyOne, &propertyTwo, &propertyThree)) for each entry into vec, then to sort just do:
sort(vec.begin(), vec.end())
If Task must be more elaborate than a tuple<property*, property*, property*>, you should define comparison operators for Task:
bool Task::operator< (const Task& rhs) {
return make_tuple(a, b, c) < make_tuple(rhs.a, rhs.b, rhs.c);
}
bool Task::operator== (const Task& rhs) {
return a == rhs.a && b == rhs.b && c == rhs.c;
}
Once these two are defined you can again do:
sort(vec.begin(), vec.end())
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