Home > OS >  How to use std::string_view with reverse iterators?
How to use std::string_view with reverse iterators?

Time:10-07

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.

CodePudding user response:

You don't need std::string_view to do this.

To implement your approach - comparing the entire string with its reverse - you can use std::equal.

bool is_palindrome(const std::string& s)
{
    return std::equal( begin(s), end(s), rbegin(s) );
}

CodePudding user response:

First it is better to have argument as std::string_view (so literals and std::string are covered without any extra allocations).

Then you need to check only half of the range and use algoritm std::equal (as in other answer).

bool is_palidrome(std::string_view s)
{
    return std::equal(begin(s), begin(s)   size(s) / 2, rbegin(s));
}

Note ADL allows to skip some std::.

  • Related