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

时间:2013-07-28 14:08:06

标签: c++ stl

对于这个例子,我们取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();
}

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

  

我在这做了什么?

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

  

我是如何重载此运算符的?

您提供了公开实施(请注意struct默认会使其成员public

  

这不是一元运算符吗?

没有。一元运算符需要一个操作数;你的运算符需要两个操作数,因此是二进制的。