K
K
keddad2020-05-18 16:38:04
C++ / C#
keddad, 2020-05-18 16:38:04

Why doesn't lower_bound see operator even though it's defined?

I have this piece of code:

bool operator<(const char l, const string& h) {
    return l < h[0];
}

template <typename RandomIt>
pair<RandomIt, RandomIt> FindStartsWith(
    RandomIt range_begin, RandomIt range_end,
    char prefix)
{
    auto left = lower_bound(range_begin, range_end, prefix);
    auto right = upper_bound(range_begin, range_end, prefix);
    return {left, right};
}


Even though operator< for char and string is explicitly defined, I still get an error when compiling:
no match for ‘operator<’ (operand types are ‘const char’ and ‘const std::__cxx11::basic_string<char>’)

CHADNT?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2020-05-18
@keddad

operator<searched through ADL. You can't define an operator for foreign types and have the algorithms pick it up. I propose this solution: instead of char, look for your own structure (it can be defined simply as a struct with char), for which you can define a comparison in the same way as you did with char.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question