patterncppModerate
Checking for a palindrome
Viewed 0 times
palindromecheckingfor
Problem
What I'm basically wondering is if there's anything that is possible to improve in this C++ code:
#include
#include
bool is_palindromic(std::string s)
{
std::size_t i = 0;
std::size_t j = s.length() - 1;
while (i < j) {
if (s[i++] != s[j--]) {
return false;
}
}
return true;
}Solution
I wanted to offer a different angle of better. This code could be more generic. Why is it tied to exactly
Note that I incorporated the other comments I agree with - in particular passing by const reference, and using the sequence's
std::string - what if I need to check palindromic nature of std::wstring or the contents of a std::vector? How about std::list or std::map (if palindromic can even mean anything on a std::map)? Here's how you can handle all of those with a single function:template
bool is_palindromic(const Sequence& seq)
{
auto count = seq.size() / 2; // rounded down is fine, as a middle element matches itself
auto i = seq.begin(); // prefer std::begin(seq) in C++14
auto j = seq.rbegin(); // prefer std::rbegin(seq) in C++14
for (Sequence::size_type c = 0; c < count; ++c, ++i, ++j)
{
if (*i != *j)
return false;
}
return true; // considers sequences without mismatched characters to be palindromes
}Note that I incorporated the other comments I agree with - in particular passing by const reference, and using the sequence's
size_type. I'm not sure how to best support arrays, however; while std::[r]begin will handle arrays, I don't believe arrays have a .size() or ::size_type to use. I guess that means they need their own overload, or at least some overloaded helpers.Code Snippets
template <typename Sequence>
bool is_palindromic(const Sequence& seq)
{
auto count = seq.size() / 2; // rounded down is fine, as a middle element matches itself
auto i = seq.begin(); // prefer std::begin(seq) in C++14
auto j = seq.rbegin(); // prefer std::rbegin(seq) in C++14
for (Sequence::size_type c = 0; c < count; ++c, ++i, ++j)
{
if (*i != *j)
return false;
}
return true; // considers sequences without mismatched characters to be palindromes
}Context
StackExchange Code Review Q#35764, answer score: 11
Revisions (0)
No revisions yet.