【问题标题】:Sorting a std::vector<QVector3D> for a specific coordinate by descending order按降序对特定坐标的 std::vector<QVector3D> 进行排序
【发布时间】:2023-03-10 19:11:02
【问题描述】:

我有一个std::vector&lt;QVector3D&gt;,其中包含一些 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 进行排序,输出应该是这样的:

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

【问题讨论】:

  • 这是否通过重载std::sorthttps://stackoverflow.com/questions/20039912/how-can-i-overload-a-custom-stdsort-comparison-function987654328@的比较函数来解决你的问题

标签: c++


【解决方案1】:
#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。 sort 函数将利用它并为您对向量数组进行排序。您还可以使用 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

【讨论】:

    【解决方案2】:

    我想按z 值对vector 进行排序。

    使用带有自定义比较器的std::sort 的重载:

    std::sort(pointVector.begin(), pointVector.end(),
              [](auto&& e1, auto&& e2) { return e1.z() < e2.z(); });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2011-06-04
      • 2011-03-25
      • 1970-01-01
      相关资源
      最近更新 更多