【发布时间】:2016-11-08 20:15:20
【问题描述】:
我正在挑战自己编写一个仅使用 SL 算法、迭代器等的回文测试器。我还想通过编程来处理原始字符串。下面,我在copy_if 算法中使用了原始指针pal,但相反,我如何定义一个迭代器到这里,即使用begin(pal) 和end(pal + size) 之类的东西?
#include <algorithm>
#include <iterator>
#include <cctype>
using namespace std;
bool isPalindrome(const char* pal) {
if (!pal) { return(false); }
int size = strlen(pal);
string pal_raw;
pal_raw.reserve(size);
// Copy alphabetical chars only (no spaces, punctuations etc.) into pal_raw
copy_if(pal, pal+size, back_inserter(pal_raw),
[](char item) {return isalpha(item); }
);
// Test if palindromic, ignoring capitalisation
bool same = equal(begin(pal_raw), end(pal_raw), rbegin(pal_raw), rend(pal_raw),
[](char item1, char item2) {return tolower(item1) == tolower(item2); }
);
return same;
}
int main(){
char pal[] = "Straw? No, too stupid a fad. I put soot on warts.";
bool same = isPalindrome(pal);
return 0;
}
额外问题:是否可以通过在equal() 内(即!isalpha(item))“就地”递增迭代器来消除对copy_if() 的需要?
【问题讨论】:
-
为什么不使用
std::string而不是char数组? -
@NathanOliver 我已经为
std::string编写了一个重载,希望也能够处理字符数组。 -
一个指针已经是一个迭代器。
-
一个字符数组/指针可以转换成一个字符串,所以你不需要一个特殊的函数。
-
@GregBrown -- 我已经为 std::string 编写了一个重载,希望也能够处理 char 数组。 -- 那是 1 行函数 -- 只需从 char* 版本中调用
std::string版本,并将转换后的 char 数组转换为std::string。
标签: c++ pointers iterator c++-standard-library stl-algorithm