C++ 数据结构,根据成员的值自动对对象进行排序
问题描述:
在 STL 中,列表是一种数据结构,可自动按数值对数字进行排序.如果元素不是数字而是类的实例,并且我希望容器根据类成员的值自动对元素进行排序,我应该使用什么样的容器?例如
In STL, list is a data structure that automatically sort the numbers by their values. If the elements are not numbers but instances of a class, and I want the container to automatically sort the elements by the value of a member of the class, what kind of container should I use? e.g.
class Rect{
double height;
double width;
double area;
};
我希望容器按矩形的area
自动排序.
I want the container to automatically sort by area
of the rectangle.
答
您有 std::multiset
用于自动排序容器:
You have std::multiset
for auto-ordering container:
std::multiset<Rect, LessArea> rects;
使用 LessArea
struct LessArea
{
bool operator ()(const Rect& lhs, const Rect& rhs) const
{
return lhs.area < rhs.area;
}
};