我必须用几句话来测试它们是否是回文,不计算空间的字符,“,”和“ - ”。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
int inputs;
for (int i=0;i<inputs;i++)
{string str;
getline(cin, str);
transform(str.begin(), str.end(), str.begin(), ::tolower);
str.erase(remove_if(str.begin(),str.end(),','),str.end());
str.erase(remove_if(str.begin(),str.end(),'-'),str.end());
str.erase(remove_if(str.begin(),str.end(),' '),str.end());
if (str == string(str.rbegin(), str.rend()))
cout << "Y ";
else
cout << "N "; }
}
问题: 在/usr/include/c++/4.9/bits/stl_algobase.h:71:0中的文件中,来自/usr/include/c++/4.9/bits/char_traits.h:39,来自/usr/include/c++/4.9 / ios:40,来自/usr/include/c++/4.9/ostream:38,来自/usr/include/c++/4.9/iostream:39,来自solution.cc:1:/usr/include/c++/4.9/bits /predefined_ops.h:实例化'bool __gnu_cxx :: __ ops :: _ Iter_pred&lt; _Predicate&gt; :: operator()(_ Iterator)[with _Iterator = __gnu_cxx :: __ normal_iterator&gt ;; _Predicate = char]':/ usr / include / c ++ / 4.9 / bits / stl_algo.h:866:28:需要'_ForwardIterator std :: __ remove_if(_ForwardIterator,_ForwardIterator,_Predicate)[with _ForwardIterator = __gnu_cxx :: __ normal_iterator&gt; ; _Predicate = __gnu_cxx :: __ ops :: _ Iter_pred]'/ usr / include / c ++ / 4.9 / bits / stl_algo.h:937:47:需要'_FIter std :: remove_if(_FIter,_FIter,_Predicate)[with _FIter = __gnu_cxx :: __ normal_iterator&gt ;; _Predicate = char]'solution.cc:12:49:从这里需要/ usr / include / c ++ / 4.9 / bits / predefined_ops.h:231:30:错误:表达式不能用作函数{return bool(_M_pred( *__它)); } ^
(对我来说完全是胡言乱语。) 任何解决方案?
答案 0 :(得分:3)
检查回文可以像
一样简单#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string str, rStr;
std::cout << "Enter String :\n";
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
rStr = str;
std::reverse(begin(str), end(str));
(rStr == str) ? std::cout << "Word is palindrone\n" : std::cout << "Word is not palindrone\n";
return 0;
}
根据需要进行修改。
要获得多个单词作为输入,请使用getline(cin, str);
答案 1 :(得分:2)
不妨展示一个与您的尝试形成鲜明对比的解决方案:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main()
{
std::string orig;
while (std::getline(std::cin, orig))
{
std::transform(orig.begin(), orig.end(), orig.begin(), ::toupper);
// erase the punctuation and spaces
orig.erase(std::remove_if(orig.begin(), orig.end(), [](char ch)
{ return ::isspace(ch) || ::ispunct(ch);}), orig.end());
std::cout << ((orig == std::string(orig.rbegin(), orig.rend()))?"Y":"N");
}
}
请注意,不需要std::reverse
,并使用erase / remove_if
成语来删除空格和标点符号。