定义类的元素的词典比较的最简单的方法是什么? [英] What's the simplest way of defining lexicographic comparison for elements of a class?

查看:109
本文介绍了定义类的元素的词典比较的最简单的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类,我想能够排序(即支持一个小于概念),它有几个数据项,所以我需要做词典排序,然后我需要这样:

If I have a class that I want to be able to sort (ie support a less-than concept), and it has several data items such that I need to do lexicographic ordering then I need something like this:

struct MyData {
  string surname;
  string forename;

  bool operator<(const MyData& other) const {
    return surname < other.surname || (surname==other.surname && forename < other.forename); }
};

这对于超过2个数据成员的任何东西来说都变得难以管理。有什么更简单的方法来实现它吗?数据成员可以是任何Comparable类。

This becomes pretty unmanageable for anything with more than 2 data members. Are there any simpler ways of achieving it? The data members may be any Comparable class.

推荐答案

随着C ++ 11的出现,这使用 std :: tie

With the advent of C++11 there's a new and concise way to achieve this using std::tie:

bool operator<(const MyData& other) const {
  return std::tie(surname, forename) < std::tie(other.surname, other.forename);
}

这篇关于定义类的元素的词典比较的最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆