How to understand this C++ palindrome code?

倖福魔咒の 提交于 2019-12-14 03:32:50

问题


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()));
}

回答1:


Taking a look at the string constructor:

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

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()

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)

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




回答2:


string::rbegin (reverse begin) is iterator to begin of your reverse string (last character of your string), and string::rend (reverse end) is the iterator to end of your reverse string (first character of your string).

The string constructor can expect two iterators to create a new string, first one, will be the begin of your string and the second one the end.

When you pass to the constructor the reverse begin and reverse end of inputString it is creating a reverse string of inputString.




回答3:


Basically, you're reversing inputString and then checking if the two strings are still equal.

rbegin() and rend() are reverse iterators. There's a string constructor that takes a beginning and ending iterator as parameters.

All string(inputString.rbegin(), inputString.rend()) does is return the reverse of inputString.



来源:https://stackoverflow.com/questions/44400246/how-to-understand-this-c-palindrome-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!