Sort vectors by more conditions than one

隐身守侯 提交于 2019-12-12 03:44:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!