mystic.06
mystic.06

Reputation: 299

Sorting a std::vector<QVector3D> for a specific coordinate by descending order

I have a std::vector<QVector3D>, which contains some 3D coordinates. I want to sort the vector by the z value.

I push four 3D points into the vector in a loop:

/* 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();
}

The output should looks like, if I sort the vector by its z coordinate:

2.50764 -190.652 -194.383
6.22275 -176.747 -189.578
24.1295 -181.255 -179.553
29.3116 -192.771 -103.172

The std::sort

Upvotes: 0

Views: 331

Answers (2)

Gideon
Gideon

Reputation: 36

#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;
    }
}

The sort function gets two vertices from the vector array to compare. The function will return true or false depending on the values of i.z and j.z . The sort function will make use of that and sort your vector array for you. You can also sort by y using i.y and j.y in the MysortFunc.

My 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

Upvotes: 1

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

I want to sort the vector by the z value.

Use the overload of std::sort that takes a custom comparator:

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

Upvotes: 0

Related Questions