本文介绍了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;
    }
};

这篇关于C++ 数据结构,根据成员的值自动对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:46