按多个条件对向量进行排序

Sort vectors by more conditions than one

本文关键字:排序 向量 条件      更新时间:2023-10-16

我在另一篇文章中问过:my_old_post

但是现在我需要更复杂的条件来对我的向量进行排序。

我有一个这样的向量:vector_points_original。 然后,如果我为每个点的 z 排序,我还有其他向量,例如:vector_points_sorted_by_Z。 但是我需要vector_sorted_by_z,然后按 y 分量对前四点和后四点进行排序。你能帮我吗?

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);

如果您需要在按y重新排序时保存z订单,则yComp = [](const auto& p1, const auto& p2) {return p1.y < p2.y && p1.z <= p2.z;};

它对性能至关重要吗?如果没有,只需将现有向量一分为二,按 Y 排序,然后将结果放回单个向量中?

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());