为什么在键类型中使用引用时 lambda 函数在 std::lower_bound 中不起作用?

Why lambda function doesn't work in std::lower_bound while using references in key type?

我写这段代码:

std::vector<std::pair<std::string, std::string>> map_ = {{"b", "1"}, {"a", "2"}};
auto iter = std::lower_bound(map_.begin(), map_.end(), key,
                                     [](auto p1, std::string& rhs) { return p1.first < rhs; });

并得到这样的编译错误:

error: no matching function for call to object of type '(lambda at /Users/bestasoff/.../static_map.h:17:38)'
        if (__comp(*__m, __value_))

但是如果我删除 &std::lower_bound 可以正常工作。

为什么?

如果您查看 std::lower_bound 中谓词的要求,您会发现它应该类似于

bool pred(const Type1 &a, const Type2 &b);

所以你不能使用引用。仅使用 const 限定符(或按值传递键)。