如何理解这个C ++回文代码?

如何理解这个C ++回文代码?

问题描述:

我最近找到了回文问题的解决方案,但是我不明白这部分代码是如何工作的(使用rbegin和rend).有人可以向我解释吗?

I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?

#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}

看看字符串构造函数:

    ...
    (7) template <class InputIterator>
    string  (InputIterator first, InputIterator last);

您可以看到可以通过迭代器创建字符串. rbegin/rend迭代器是InputIterators,它指向它们所引用的相反位置:

You can see it is possible to create a string via iterators. The rbegin/rend iterators are InputIterators that points to the reverse positions that they refer:

    rend() -->"My string"<-- rbegin()

也就是说,当您将rbegin()和rend()传递给字符串构造函数时,它将从字符串的结尾开始迭代到字符串的开头,从而创建反向的字符串:

That said, when you pass the rbegin() and rend() to the string constructor, it will iterate from the ending, to the beginning of the string, creating the inverted one:

    iteration 0: "g"    (currentIterator = rbegin()   : push("g")
    iteration 1: "n"    (currentIterator = rbegin()+1 : push("n")
    iteartion 2: "i"    (currentIterator = rbegin()+2 : push("i")
    ...
    iteration 8: "M"    (currentIterator = rbegin()+8 : push("M")
    iteration 9: rend() (currentIterator = rend()     : stop iteration)

最后,operator ==()将检查字符串的等效性.

Finally, the operator==() will check for equivalence of the strings.