#include <iostream>
#include <string>
using namespace std;
string reversal(string a) {
int i = a.length();
string reversed_string{};
for (; i >= 0; --i)
reversed_string += a[i];
return reversed_string;
}
bool palindrome(string a) {
if (a == reversal(a)) {
cout << "this is a palindrome " << endl;
return true;
}
else if(a != reversal(a))
{
cout << "this is not a palindrome " << endl;
return false;
}
}
int main(){
}这是我为回文程序编写的程序,查找字符串的相反部分不那么繁琐,但是回文函数不起作用,我不明白为什么。
发布于 2022-10-25 14:15:04
大量的空白并不能提高可读性。函数之间的空白行很好,偶尔在任何其他地方都需要单独的空行来分离逻辑组。
避免using namespace std;。它可能导致意外的重载,并使代码更难阅读(因为标识符的来源不再明显)。
通过使用reversal()确保结果字符串从一开始就具有正确的容量,可以提高reserve()的效率。也就是说,使用字符串的反向迭代器构造反向字符串比较简单:
std::string reversed_string{a.rbegin(), a.rend()};但我们实际上不需要分配一个新字符串并将其复制到其中。如果我们使用std::equal()算法,我们只需传递两个迭代器对:
#include <algorithm>if (std::equal(a.begin(), a.end(), a.rbegin(), a.rend())从C++20开始,我们就能够使用Range获得字符串的反向视图并进行比较:
#include <algorithm>
#include <ranges>if (std::ranges::equal(a, a | std::ranges::reverse))谓词函数通常以is_或has_开头命名--在这里,我们编写is_palindrome()。我们不需要我们自己的a副本,所以请参考const。
不喜欢在谓词函数中生成输出--只返回结果。调用者可能选择打印结果,或者将其用于其他事情。当您生成输出时,不要在没有充分理由的情况下刷新流--即更喜欢'\n'而不是std::endl。
我们当然不需要逆转a两次-- else if可以是普通的else。更简单地说,由于两个分支都分别返回true或false,所以我们只需返回比较结果:
#include <algorithm>
#include <ranges>
#include <string>
bool is_palindrome(const std::string& a)
{
return std::ranges::equal(a, a | std::views::reverse);
}由于我们只需要比较字符串的前半部分和后半部分(在该点之后继续操作是多余的),这仍然需要做更多的工作。因此,我们可以通过使用子范围视图( size() / 2 )来比较第一个std::views::take元素。
这里是我们的结局--没有S创造的std::string,也没有不必要的比较:
#include <algorithm>
#include <ranges>
#include <string_view>
bool is_palindrome(const std::string_view a)
{
auto const halflen = a.size() / 2;
return std::ranges::equal(a | std::views::take(halflen),
a | std::views::reverse | std::views::take(halflen));
}#include <iostream>
int main()
{
for (auto const& s: { "", "0", "abc", "racecar" }) {
std::cout << '"' << s << "\" "
<< (is_palindrome(s) ? "is a palindrome" : "is not a palindrome")
<< '\n';
}
}https://codereview.stackexchange.com/questions/280724
复制相似问题