How to sort a multidimensional vector of floats?

后端 未结 3 1767
一向
一向 2021-01-23 14:59

So, I have a set of points in 3D, and I would like to store them in a 3 dimensional vector. Then I need sort that vector, giving priority first to the X dimention, then Y, then

3条回答
  •  没有蜡笔的小新
    2021-01-23 15:04

    You can use the std::sort() to easily sort according to your specific conditions by making your own comparator function.

    Assuming you have stored a single 3D point in a struct point, and the points in a std::vector (A std::tuple might be more useful.), try out this code.

    Example:

    #include 
    #include 
    using namespace std;
    struct point
    {
         float x, y, z;
    }
    bool mySort(const point& a, const point& b)
    {
        //A naive comparison to help you understand better.
        //You could always use std::tie for lexicographical comparison.
        if (a.x == b.x)
        {
            if (a.y == b.y)
                return a.z < b.z;
            else
                return a.y < b.y;
        }
        else
            return a.x < b.x;
    }
    int main()
    {
        vector graph;
        //push_back() all your points into the graph.
        //mySort() is a custom comparator function.
        sort(graph.begin(),graph.end(),mySort); 
    }
    

提交回复
热议问题