问题
I asked in other post about: my_old_post
But now I need more complex condition to sort my vector.
I have a vector like this: vector_points_original. Then if I sort it for z of each point I have other vector like: vector_points_sorted_by_Z. But I need vector_sorted_by_z and after sort first four points and second four points by y component. Could you help me?
回答1:
std::vector<CartesianPoint>v{...};//place your values here
//First, sort by Z
std::sort(v.begin(), v.end(), [](const auto& p1, const auto& p2){return p1.z < p2.z;});
//Define a compare-by-y lambda
auto yComp = [](const auto& p1, const auto& p2){return p1.y < p2.y;};
//Use yComp for first 4 v[]
std::sort(v.begin(), v.begin() + 4, yComp);
//And for the second
std::sort(v.begin() + 4, v.begin() + 8, yComp);
If you need to save z
order while reordering by y
, then yComp = [](const auto& p1, const auto& p2) {return p1.y < p2.y && p1.z <= p2.z;};
回答2:
Is it performance critical ? If not, just split your existing vector into two, sort by Y and then put the results back into a single vector ?
std::vector<Point3d> sortedByZ;
std::vector<Point3d> firstFour(sortedByZ.begin(), sortedByZ.begin() + 4);
std::vector<Point3d> lastFour(sortedByZ.begin() + 5, sortedByZ.end());
// Sort firstFour and lastFour independently
sortedByZ = firstFour;
sortedbyZ.insert(sortedByZ.end(), lastFour.begin(), lastFour.end());
?
来源:https://stackoverflow.com/questions/42863359/sort-vectors-by-more-conditions-than-one