对于具有两个 int 成员的简单类,正确的 less 运算符是什么?
以下类的正确运算符<
是什么?
struct Person {
int height;
int width;
friend bool operator<(const Person&, const Person&);
};
谢谢!
What is the correct operator<
for the following class?
struct Person {
int height;
int width;
friend bool operator<(const Person&, const Person&);
};
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这完全取决于您以及您希望人们如何自然排序。如果您希望先矮个子,但如果身高相同,则先瘦后高:
如果您想测量一个人的表面积来确定顺序:
That's entirely up to you and how you would want people to naturally sort. If you want short people first, but skinny to come before tall if they are the same height:
If you want some measure of a person's surface area to determine ordering:
取决于您想要排列/排序人员实例的方式。一个例子是
,先看高度(按最短的先排列),如果高度相同,再看宽度,先按较窄的排列。
Depends on the way you want to arrange/sort instances of person. An example would be
i.e. first look at height (arranging by shortest first) , if heights are same, look at width, arranging by narrower first.
我的样板方法:
但如果可以的话,请考虑使用
pair
的 typedef。这有点毫无意义地使用所有可用数据来排序。 (这里,首先按宽度排序,如果宽度相等,则按高度排序。)如果您仅使用排序来查找相同的元素,那么这可能就是您想要的。
My boilerplate way of doing it:
But consider using a typedef of
pair<int, int>
instead, if you can.This somewhat meaninglessly orders things using all available data. (Here things are ordered first by width, and then by height if widths are equal.) If you are only using the ordering to find identical elements, that's probably what you want.
为了将类放入集合中,您还需要处理运算符==。根据 Person 类中的数据,我认为您无法定义一个好的运算符==。或者你的意思是两个具有相同宽度和高度的人是相同的?我将添加一些唯一标识符,允许为 Person 定义完整的订单。
如果您没有更多信息,您可以使用另一个答案中指出的字典顺序。
但切勿使用面积来对它们进行排序,否则您需要根据面积定义相等性,然后 (4,5) == (5,4) 才能获得完整的顺序。我想你不希望这样。请注意,如果 !((4,5) < (5,4)) 且 (4,5) != (5,4),我们可以推断 (5,4) < (5,4)) (4,5),这也是错误的。
如果您不使用集合的有序性质,您可以考虑使用 unordered_set 或哈希表。但无论如何,您都需要处理运算符==。
In order to put a class in a set you also need to take care of operator==. With the data you have in the class Person I don't think you can define a good operator==. Or are you meaning that two Persons having the same width and height are the same? I will add some unique identifier that allows to define a complete order for Person.
If you have no more information, you can use lexicographic order as pointed on another answer.
But never use the area to order them, otherwise you will need to define equality depending on the area and then (4,5) == (5,4) to get a complete order. I suppose you don't want that. Note that if !((4,5) < (5,4)) and (4,5) != (5,4), we can deduce that (5,4) < (4,5), which is false too.
If you are not using the ordered nature of a set, you could think of using a unordered_set or a hash table. But in any case you will need to take care of operator==.