stl 容器的"less"参数如何工作?

How does stl containers' `less` parameter works?

本文关键字:工作 何工作 参数 less stl      更新时间:2023-10-16

map为例。

我设置了映射对象:map<const char*, int, compare> a,因为compare如下:

struct compare : public std::binary_function<const char*, const char*, bool>
{
    bool operator() (const char* a, const char* b) {
        return strcmp(a, b) < 0;
    }
};

我在这里做了什么?我是如何使这个操作员过载的?那不是一元运算符吗?

它起作用了,但我不确定我是否真的知道我在这里写了什么。

这是完整的代码:

#include <set>
#include <map>
#include <string>
#include <iostream>
using namespace std;
struct compare : public std::binary_function<const char*, const char*, bool>
{
    bool operator() (const char* a, const char* b) {
        return strcmp(a, b) < 0;
    }
};
int main() {
    map<const char*, int, compare> a;
    a["Mike"] = 5;
    a["Tre"] = 3;
    a["Billie"] = 20;
    for(map<const char*, int, compare>::iterator it = a.begin(); it != a.end(); ++it) {
        cout << (*it).first << endl;
    }
    cin.get();
}

您的compare定义允许以下内容:

compare cmp;
bool result = cmp("foo", "bar");  // Two arguments, therefore not unary!

因此std::map可以使用它来确定元素对的相对排序。这是在幕后构建二进制搜索树所必需的。

我在这里做了什么?

您创建了一个函数对象,该对象提供了operator ()的实现,并提供了它的类来实例化std::map模板。

我是如何使这个操作员过载的?

您提供了它的公共实现(请注意,默认情况下struct使其成员为public)。

那不是一元运算符吗?

没有。一元运算符取一个操作数;您的运算符接受两个操作数,因此是二进制的。