-4
class Polygon3D
{
public:
    float GetDepth() const
    {
    return _depth;
    }
private:
    float _depth;
};

class Model
{
public:
    void Sort(void);
    {
    std::sort(_polygons.begin(), _polygons.end(), SortMethod);
    }
private:
    std::vector<Polygon3D> _polygons;
    static bool SortMethod(const Polygon3D& lhs, const Polygon3D& rhs)
    {
        return lhs.GetDepth() < rhs.GetDepth();
    }
};

I hope the code above is enough to explain what I'm trying to do, which is sort by depth. However, despite the polygons having differing depths, the sort doesn't seem to do anything. Tried looking at other questions but couldn't find an answer, so not sure what I'm missing. Thanks.

Nerdy Wizard
  • 53
  • 1
  • 10

1 Answers1

0

Use a 'functor' (function object - an object/class that works like a function by overloading operator()):

#include <vector>
#include <algorithm>

class Polygon3D
{
public:
    Polygon3D(float depth) : _depth(depth) {}

    float GetDepth() const
    {
        return _depth;
    }
private:
    float _depth;
};

class Model
{
public:
    void InsertPolygon(Polygon3D polygon)
    {
        _polygons.push_back(polygon);
    }

    void Sort()
    {
        std::sort(_polygons.begin(), _polygons.end(), Model());
    }

    bool operator() (const Polygon3D& lhs, const Polygon3D& rhs) const
    {
        return (lhs.GetDepth() < rhs.GetDepth());
    }
private:
    std::vector<Polygon3D> _polygons;
};


int main()
{
    Model model;

    for (int i = 0; i < 10; ++i)
        model.InsertPolygon(Polygon3D(std::rand()));

    model.Sort();

    return 0;
}

Or you can overload Polygon3D's operator<, so you can call std::sort without having to specify a custom comparison functor:

#include <vector>
#include <algorithm>    

class Polygon3D
{
public:
    Polygon3D(float depth) : _depth(depth) {}

    bool operator < (const Polygon3D& rhs) const
    {
        return (this->GetDepth() < rhs.GetDepth());
    }

    float GetDepth() const
    {
        return _depth;
    }

private:
    float _depth;
};

class Model
{
public:
    void InsertPolygon(Polygon3D polygon)
    {
        _polygons.push_back(polygon);
    }

    void Sort()
    {
        std::sort(_polygons.begin(), _polygons.end());
    }
private:
    std::vector<Polygon3D> _polygons;
};


int main()
{
    Model model;

    for (int i = 0; i < 10; ++i)
        model.InsertPolygon(Polygon3D(std::rand()));

    model.Sort();

    return 0;
}

Btw, you will generally receive much better response from people here if you post a minimal but verifiable example (i.e. one that we can copy/paste & compile without having to make changes).

not an alien
  • 651
  • 4
  • 13