I am trying to create a very simple function:
bool is_palidrome(const std::string& s)
{
std::string r(s.crbegin(), s.crend());
return s==r;
}
In order to avoid unnecessary allocations I thought I could use a string_view:
bool is_palidrome(const std::string& s)
{
std::string_view r(s.crbegin(), s.crend());
return s==r;
}
However the last function fails to compile since the compiler cannot find a suitable constructor (I tried both g++ 12.2 and clang++ 15.0).
Why there isn't a constructor for this case while std::string_view r(s.cbegin(), s.cend()); works perfectly? I check the standard https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view but I do not see which condition is not satisfied.
==will compare the whole string, while a loop as described above will only compare half the string.is_palandromewithout allocating. "Usingstd::string_viewwith reverse iterators" is not the solution, however.Length / 2iterations comparing 2-characters per-iteration:)