我有一个std::vector<QVector3D>,它包含一些3D坐标。我想按z值对vector进行排序。
我将四个三维点推入一个循环中的向量中:
/* 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进行排序,输出应该如下所示:
2.50764 -190.652 -194.383
6.22275 -176.747 -189.578
24.1295 -181.255 -179.553
29.3116 -192.771 -103.172std::排序
发布于 2021-02-27 23:16:59
#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;
}
}排序函数从向量数组中获取两个顶点进行比较。该函数将根据i.z和j.z的值返回true或false。排序函数将利用这一点并为您对向量数组进行排序。您还可以在MysortFunc中使用i.y和j.y按y排序。
我的输出:
2.50764 190.652 194.383
6.22275 176.747 189.578
24.1295 181.255 179.553
29.3116 192.771 103.172发布于 2021-02-27 23:01:25
我想按
z值对vector进行排序。
使用采用自定义比较器的std::sort重载:
std::sort(pointVector.begin(), pointVector.end(),
[](auto&& e1, auto&& e2) { return e1.z() < e2.z(); });https://stackoverflow.com/questions/66400013
复制相似问题