简体   繁体   中英

How to use std::string_view with reverse iterators?

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.

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

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:: .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM