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).