Gre*_*own 4 c++ pointers iterator c++-standard-library stl-algorithm
我正在挑战自己只使用 SL 算法、迭代器等编写回文测试器。我还想编写程序以使用原始字符串。下面,我pal在copy_if算法中使用了原始指针,但相反,我如何定义一个迭代器来这里,即使用类似begin(pal)and 的东西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;
}
Run Code Online (Sandbox Code Playgroud)
额外问题:是否可以copy_if() 通过从内部equal()ie when增加“就地”迭代器来消除需要!isalpha(item)?
当涉及到 C++ 库算法时,迭代器实现了指针的概念。而且,正如您所发现的,采用迭代器的 C++ 库算法也非常乐意采用指针。这是相同的概念。
当您已经有指针开始时,就没有某种迭代器可以将指针转换为。
确实如此
std::begin(arr)
Run Code Online (Sandbox Code Playgroud)
和
std::end(arr)
Run Code Online (Sandbox Code Playgroud)
在平面阵列上定义。但是,你猜怎么着:它们返回一个指向数组开头和结尾的指针,而不是某种迭代器类。
但是,您不能使用std::begin(),std::end()因为当您需要使用它时,在您的函数内部,数组已经衰减为char *。std::begin()和std::end()适用于真正的数组,而不是衰减的指针。
如果您坚持使用迭代器,您应该将 a 传递std::string给您的回文函数,而不是 a char *。std::string实现 abegin()和一个end()返回 a的方法std::string::iterator,您可以使用。
| 归档时间: |
|
| 查看次数: |
3936 次 |
| 最近记录: |