[英]Sorting a std::vector<QVector3D> for a specific coordinate by descending order
我有一个std::vector<QVector3D>
,其中包含一些 3D 坐标。 我想按z
值对vector
进行排序。
我将四个 3D 点推入循环中的向量中:
/* points
29.3116 -192.771 -103.172
2.50764 -190.652 -194.383
24.1295 -181.255 -179.553
6.22275 -176.747 -189.578
*/
// Find the points and push in vector
...
std::vector<QVector3D> pointVector;
pointVector.push_back(QVector3D(point[0], point[1], point[2]));
// iterate through vector
for(int i= 0; i< pointVector.size(); i++)
{
qDebug()<<"Vector: " << pointVector[i].x() << pointVector[i].y() << pointVector[i].z();
}
如果我按z
坐标对vector
进行排序,output 应该看起来像:
2.50764 -190.652 -194.383
6.22275 -176.747 -189.578
24.1295 -181.255 -179.553
29.3116 -192.771 -103.172
std::sort
#include <iostream>
#include <vector>
#include <algorithm>
struct vec3
{
float x;
float y;
float z;
};
bool MysortFunc(const vec3& i, const vec3& j) { return (i.z > j.z); }
int main() {
std::vector<vec3> vertices;
vertices.push_back({ 29.3116 , 192.771 , 103.172 });
vertices.push_back({ 2.50764 , 190.652 , 194.383 });
vertices.push_back({ 24.1295 , 181.255 , 179.553 });
vertices.push_back({ 6.22275 , 176.747 , 189.578 });
std::sort (vertices.begin(), vertices.end(), MysortFunc);
for (auto vertex : vertices)
{
std::cout << vertex.x << ' ' << vertex.y << ' ' << vertex.z << std::endl;
}
}
排序 function 从向量数组中获取两个顶点进行比较。 function 将根据 iz 和 jz 的值返回 true 或 false 排序 function 将利用它并为您对向量数组进行排序。 您还可以在 MysortFunc 中使用 iy 和 jy 按 y 排序。
我的 output:
2.50764 190.652 194.383
6.22275 176.747 189.578
24.1295 181.255 179.553
29.3116 192.771 103.172
我想按
z
值对vector
进行排序。
使用带有自定义比较器的std::sort
重载:
std::sort(pointVector.begin(), pointVector.end(),
[](auto&& e1, auto&& e2) { return e1.z() < e2.z(); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.