Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

algorithm - How to understand this C++ palindrome code?

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()));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...