C ++集合未排序

时间:2018-11-27 11:50:11

标签: c++ sorting

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

我希望上面的代码足以解释我要做什么,按深度排序。但是,尽管多边形的深度不同,但排序似乎没有任何作用。尝试查看其他问题,但找不到答案,所以不确定我要缺少什么。 谢谢。

1 个答案:

答案 0 :(得分:0)

使用'functor'(函数对象-通过重载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;
}

或者您可以重载Polygon3D的{​​{1}},因此您可以调用operator<,而不必指定自定义比较函子:

std::sort

顺便说一句,如果您发布一个最小但可验证的示例(例如,我们可以进行复制/粘贴和编译而无需进行更改),通常会收到来自此处人员的更好答复。

相关问题