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

177 views Asked by At

I write this code:

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; });

and get such compile error:

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

But if I drop &, std::lower_bound works properly.

Why?

1

There are 1 answers

4
dasfex On BEST ANSWER

If you look at the requirements for the predicate in std::lower_bound you will see that it should look like

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

So you can't use reference. Only with const qualifier(or pass key by value).