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



我写的代码是:

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限定符(或按值传递密钥(。

最新更新