简体   繁体   中英

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

#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 iz and jz The sort function will make use of that and sort your vector array for you. You can also sort by y using iy and jy 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM