为具有自定义键的C++映射编写自定义比较器自定义

2023-09-03 12:14:45 作者:年少轻狂。

我正在尝试为具有自定义键的C++映射编写自定义比较器。

struct key { int year; int no; };
map<key, detail, compare> details_map;

如果year值相等,则它必须比较no值。

台式音量快捷健问题

我正在尝试找出一种方法来编写可以比较这两个值的比较器。到目前为止,我只能编写一个比较一个值的比较器。

struct Compare{bool operator()(const key &lhs,const key &rhs)const{return lhs.year<rhs.year;}}

谁能解释一下map中比较器的工作原理吗?

另外,是否可以将比较器编写为函数?

推荐答案

在您的operator()中,如果year值相等,只需比较no值:

struct Compare {
    bool operator()(const key &lhs, const key &rhs) const {
        if (lhs.year == rhs.year) {
            return lhs.no < rhs.no;
        }
        return lhs.year < rhs.year;
    }
};

是的,比较器可以作为独立函数实现:

bool Compare (const key &lhs, const key &rhs) {
    if (lhs.year == rhs.year) {
        return lhs.no < rhs.no;
    }
    return lhs.year < rhs.year;
}
或者,您可以让您的比较器使用std::tie()来比较您的关键字字段。请参阅@Jarod42's answer。

但是,为您的key类型实现operator<会更有意义:

struct key {
    int year;
    int no;

    bool operator<(const key &rhs) const {
        if (year == rhs.year) {
            return no < rhs.no;
        }
        return year < rhs.year;
    }
};

struct key {
    int year;
    int no;
};

bool operator<(const key &lhs, const key &rhs) {
    if (lhs.year == rhs.year) {
        return lhs.no < rhs.no;
    }
    return lhs.year < rhs.year;
}

那么您不需要单独的比较器:

map<key, detail> details_map;